Regular Expressions in Java
Regular expressions (regex) are sequences of characters that define a search pattern. Java provides full regex support through the java.util.regex package,...
Pattern Matching with Java Regex
Regular expressions (regex) are sequences of characters that define a search pattern. Java provides full regex support through the java.util.regex package, which contains two key classes: Pattern and Matcher. Pattern compiles a regex string into an efficient internal representation, and Matcher applies that pattern to a specific input string to find, test, or replace matches.
Core Regex Syntax A dot (.) matches any single character. Square brackets like [aeiou] match any character inside them. The star (*) means zero or more repetitions, plus (+) means one or more, and question mark (?) means zero or one. Curly braces specify exact counts: {3} means exactly three times and {2,5} means between two and five times. The caret (^) anchors to the start of the string and the dollar sign ($) anchors to the end. Backslash sequences like \d match digits, \w matches word characters, and \s matches whitespace.
Using Pattern and Matcher First compile the pattern: Pattern p = Pattern.compile("[A-Z][a-z]+"). Then create a matcher: Matcher m = p.matcher(inputString). Call m.matches() to check whether the entire input matches, or m.find() to search for the pattern anywhere within the string. After find() returns true, m.group() returns the matched substring and m.start() and m.end() give its position.
Convenient Shortcut Methods String provides two regex-powered methods directly. str.matches(regex) returns true only if the entire string matches the pattern—it automatically wraps the pattern in ^ and $. str.replaceAll(regex, replacement) replaces every match with the given replacement text. str.split(regex) splits the string at every match of the pattern. These shortcuts are convenient but create a new Pattern object each call, so for repeated use compile the pattern once with Pattern.compile().
Code Example: Pattern emailPattern = Pattern.compile("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}"); Matcher m = emailPattern.matcher("[email protected]"); System.out.println(m.matches()); // true System.out.println("hello123".matches("[a-z]+\\d+")); // true
Interview Tip: Know the difference between matches() and find(). matches() requires the entire string to match the pattern, while find() searches for the pattern anywhere in the string. This trips up many candidates. Also be ready to explain why double backslashes are needed in Java string literals for regex escapes—the first backslash escapes the second for the Java compiler, and the resulting single backslash is interpreted by the regex engine.