Java - Regular Expressions Part 4: Advanced Regex Constructs
Groups and Capturing
Pattern pattern = Pattern.compile("(\\d{2})-(\\d{2})-(\\d{4})");
Matcher matcher = pattern.matcher("Date: 12-08-2024");
if (matcher.find()) {
System.out.println("Day: " + matcher.group(1)); // Day: 12
System.out.println("Month: " + matcher.group(2)); // Month: 08
System.out.println("Year: " + matcher.group(3)); // Year: 2024
}
Boundary Matchers
\b: Word boundaries.
\d: Matches any digit.
Pattern pattern = Pattern.compile("\\b\\w+\\b");
Matcher matcher = pattern.matcher("Hello world!");
while (matcher.find()) {
System.out.println("Word: " + matcher.group());
}
// Word: Hello
// Word: world
Lookahead
Pattern pattern = Pattern.compile("\\d+(?= dollars)");
Matcher matcher = pattern.matcher("Price is 300 dollars");
if (matcher.find()) {
System.out.println("Amount: " + matcher.group()); // Amount: 300
}
Negative Lookbehind
Pattern pattern = Pattern.compile("(?<!USD )\\d+");
Matcher matcher = pattern.matcher("Price is USD 300");
if (matcher.find()) {
System.out.println("Amount: " + matcher.group()); // No match
}