Search, match, and replace text patterns with Java’s Pattern and Matcher classes — the practical patterns you’ll actually use.
Why: a regular expression (regex) describes a pattern of text. The quick way to test a whole string is String.matches(). Note that in Java strings a backslash must be doubled, so \\d in the code means the regex \d (a digit).
String code = "12345";
System.out.println(code.matches("\\d+")); // true — all digits
System.out.println("12a45".matches("\\d+")); // false — has a letterWhy: a handful of symbols cover most real needs. \d is a digit, \w is a letter/number/underscore, \s is whitespace, . is any character, + means "one or more", * means "zero or more", and {2,4} means "between 2 and 4".
// a simple email-ish pattern
String pattern = "\\w+@\\w+\\.\\w+";
System.out.println("a@x.com".matches(pattern)); // true
// exactly 4 digits
System.out.println("2026".matches("\\d{4}")); // true
System.out.println("123".matches("\\d{4}")); // falseWhy: matches() checks the whole string. To find a pattern anywhere — possibly many times — compile a Pattern once and run a Matcher over the text, looping with find().
import java.util.regex.Pattern;
import java.util.regex.Matcher;
Pattern p = Pattern.compile("\\d{3}-\\d{4}");
Matcher m = p.matcher("Call 555-1234 or 555-5678");
while (m.find()) {
System.out.println(m.group()); // 555-1234, then 555-5678
}Why: parentheses ( ) capture part of a match so you can pull it out separately. group(1) is the first captured piece — handy for splitting structured text like dates.
import java.util.regex.Pattern;
import java.util.regex.Matcher;
Pattern p = Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})");
Matcher m = p.matcher("2026-06-17");
if (m.find()) {
System.out.println(m.group(1)); // "2026" (year)
System.out.println(m.group(2)); // "06" (month)
}Why: replaceAll swaps every match for new text in one call — the everyday tool for cleaning or masking strings.
String text = "Call 555-1234 or 555-5678";
String masked = text.replaceAll("\\d{3}-\\d{4}", "[hidden]");
System.out.println(masked); // "Call [hidden] or [hidden]"