Regular Expressions
A regular expression (regex) is a pattern used to search, match, or manipulate text. Java's support lives in the java.util.regex package, built around two classes: Pattern, a compiled representation of a regex, and Matcher, which applies that pattern to a specific piece of text.
A Quick One-Off Check: String.matches()
For a single, throwaway check, String has a convenience method that skips Pattern/Matcher entirely.
String.matches() for a quick check
public class QuickMatchDemo {
public static void main(String[] args) {
String input = "12345";
boolean isNumeric = input.matches("\\d+"); // one or more digits
System.out.println(isNumeric);
}
}true
Pattern and Matcher
String.matches() is convenient, but it recompiles the pattern on every call and only tells you yes/no. Pattern.compile() lets you reuse a compiled pattern, and Matcher lets you find matches, extract them, or replace them.
Compiling a pattern and finding matches
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternMatcherDemo {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("\\b[A-Z][a-z]*\\b");
Matcher matcher = pattern.matcher("Alice met Bob near the River");
while (matcher.find()) {
System.out.println("Found: " + matcher.group());
}
}
}Found: Alice Found: Bob Found: River
Common Use Cases
Use case | Example pattern (Java string literal) |
|---|---|
Validate a simple email format |
|
Match one or more digits |
|
Match whitespace |
|
Match a word boundary |
|
Extract groups with parentheses |
|
Validating an email format
import java.util.regex.Pattern;
public class EmailValidationDemo {
private static final Pattern EMAIL_PATTERN =
Pattern.compile("^[\\w.+-]+@[\\w-]+\\.[a-zA-Z]{2,}$");
public static void main(String[] args) {
String[] candidates = { "user@example.com", "not-an-email" };
for (String candidate : candidates) {
boolean valid = EMAIL_PATTERN.matcher(candidate).matches();
System.out.println(candidate + " -> " + valid);
}
}
}user@example.com -> true not-an-email -> false
Extracting Parts of a String With Groups
Parentheses () in a pattern create capturing groups, letting you pull specific pieces out of a larger match rather than just checking whether the whole string matches.
Extracting a phone number's area code and number
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GroupExtractionDemo {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("\\((\\d{3})\\)\\s*(\\d{3}-\\d{4})");
Matcher matcher = pattern.matcher("Call (555) 123-4567 for support");
if (matcher.find()) {
System.out.println("Area code: " + matcher.group(1));
System.out.println("Number: " + matcher.group(2));
}
}
}Area code: 555 Number: 123-4567
Pattern.compile()compiles a regex once for reuse;Matcherapplies it to actual text.String.matches()is a quick shortcut for a single yes/no check.Because the Java string escape character is a backslash, regex escapes must be doubled in source: two backslashes plus a letter (like d) become one backslash for the regex engine.
Parentheses create capturing groups, retrieved with
matcher.group(n).