Examples
Check a given string regex pattern is valid or not
try {
// Try to compile the regex pattern
Pattern.compile(patternString);
System.out.println("Valid");
} catch (PatternSyntaxException e) {
// If there's a syntax error, catch it and print Invalid
System.out.println("Invalid");
}Simple Matching
Matching a phone number
import java.util.regex.*;
public class SimpleMatchingExample {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("\\d{3}-\\d{3}-\\d{4}");
Matcher matcher = pattern.matcher("My phone number is 123-456-7890.");
if (matcher.find()) {
System.out.println("Phone number found: " + matcher.group()); //Phone number found: 123-456-7890
} else {
System.out.println("No phone number found.");
}
}
}Lookaheads and Lookbehinds
Lookahead Example
Capturing Groups
Match a date in the format MM/DD/YYYY and extract the month, day, and year.
MM/DD/YYYY and extract the month, day, and year.Named Capturing Groups to extract month, day, and year.
Nested Capturing Groups to extract first and last names from full name
Replacing Text
Replace all instances of the word "apple" with "orange"
Using Groups in Replacement to reverse the order of the first and last names
Conditional Replacement with a Function to transform the text
Practical Use Cases
1. Validating Email Addresses
2. Parsing URLs
3. Data Extraction from Logs
4. Extracting Dates from Text
Last updated