Java - Regular Expressions Part 3: Pattern and Matcher Classes
Example 1: Finding All Matches
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher("Order123, Item456");
while (matcher.find()) {
System.out.println("Match: " + matcher.group());
}
// Match: 123
// Match: 456
Example 2: Using group()
Pattern pattern = Pattern.compile("(\\w+)@(\\w+\\.com)");
Matcher matcher = pattern.matcher("[email protected]");
if (matcher.find()) {
System.out.println("User: " + matcher.group(1)); // User: user
System.out.println("Domain: " + matcher.group(2)); // Domain: example.com
}
Example 3: Start and End Index
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher("Price is 300 dollars");
if (matcher.find()) {
System.out.println("Start: " + matcher.start() + ", End: " + matcher.end());
}
// Start: 9, End: 12
Example 4: Checking Entire Match
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher("12345");
System.out.println("Entire match: " + matcher.matches()); // true