// Simple match
boolean matches = Pattern.matches("\\d+", "123"); // true
// Compile pattern for reuse
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher("abc123def456");
// Find all matches
while (matcher.find()) {
System.out.println("Found: " + matcher.group());
System.out.println("Start: " + matcher.start());
System.out.println("End: " + matcher.end());
}
// Replace all
String text = "Hello World World";
String replaced = text.replaceAll("World", "Java");
// Result: "Hello Java Java"
// Replace first
String replacedFirst = text.replaceFirst("World", "Java");
// Result: "Hello Java World"
// Split by pattern
String input = "one,two,three";
String[] parts = input.split(",");
// Result: ["one", "two", "three"]
// Extract groups
Pattern datePattern = Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})");
Matcher dateMatcher = datePattern.matcher("2024-01-15");
if (dateMatcher.matches()) {
String year = dateMatcher.group(1); // "2024"
String month = dateMatcher.group(2); // "01"
String day = dateMatcher.group(3); // "15"
}
// Email validation
String email = "[email protected]";
boolean isValid = email.matches("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$");
// Find and replace with groups
String text2 = "Hello John, Hello Jane";
String result = text2.replaceAll("Hello (\\w+)", "Hi $1");
// Result: "Hi John, Hi Jane"