Java Regular Expressions
Pattern matching and text manipulation using regex patterns with Pattern and Matcher classes
java (1.4+)
2025-11-03
regex
pattern-matching
validation
text-processing
Description
Java’s regular expression support through the java.util.regex package provides powerful pattern matching capabilities. Regular expressions are useful for validation, searching, replacing, and parsing text.
Key Classes
- Pattern: Compiled representation of a regular expression
- Matcher: Engine that performs match operations on a character sequence
- PatternSyntaxException: Unchecked exception indicating syntax error in regex
Common Patterns
- Email validation:
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ - Phone numbers:
^\+?[1-9]\d{1,14}$ - URLs:
^https?://[\w\-.]+(\.[\w\-.]+)*([\w\-\.,@?^=%&:/~+#]*)?$ - Dates:
^\d{4}-\d{2}-\d{2}$
Common Operations
- Match: Check if pattern matches entire string
- Find: Search for pattern in string
- Replace: Replace matches with new text
- Split: Split string by pattern
Code
import java.util.regex.*;import java.util.*;public class RegexUtils { // Check if pattern matches public static boolean matches(String pattern, String input) { return Pattern.matches(pattern, input); } // Find all matches public static List<String> findAllMatches(String pattern, String input) { List<String> matches = new ArrayList<>(); Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(input); while (m.find()) { matches.add(m.group()); } return matches; } // Replace all matches public static String replaceAll(String pattern, String input, String replacement) { return input.replaceAll(pattern, replacement); } // Replace first match public static String replaceFirst(String pattern, String input, String replacement) { return input.replaceFirst(pattern, replacement); } // Split by pattern public static String[] split(String pattern, String input) { return input.split(pattern); } // Validate email public static boolean isValidEmail(String email) { String pattern = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"; return Pattern.matches(pattern, email); } // Extract groups public static List<String> extractGroups(String pattern, String input) { List<String> groups = new ArrayList<>(); Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(input); if (m.find()) { for (int i = 0; i <= m.groupCount(); i++) { groups.add(m.group(i)); } } return groups; } // Validate phone number public static boolean isValidPhone(String phone) { String pattern = "^\\+?[1-9]\\d{1,14}$"; return Pattern.matches(pattern, phone); }}
// Simple matchboolean matches = Pattern.matches("\\d+", "123"); // true// Compile pattern for reusePattern pattern = Pattern.compile("\\d+");Matcher matcher = pattern.matcher("abc123def456");// Find all matcheswhile (matcher.find()) { System.out.println("Found: " + matcher.group()); System.out.println("Start: " + matcher.start()); System.out.println("End: " + matcher.end());}// Replace allString text = "Hello World World";String replaced = text.replaceAll("World", "Java");// Result: "Hello Java Java"// Replace firstString replacedFirst = text.replaceFirst("World", "Java");// Result: "Hello Java World"// Split by patternString input = "one,two,three";String[] parts = input.split(",");// Result: ["one", "two", "three"]// Extract groupsPattern 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 validationString email = "[email protected]";boolean isValid = email.matches("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$");// Find and replace with groupsString text2 = "Hello John, Hello Jane";String result = text2.replaceAll("Hello (\\w+)", "Hi $1");// Result: "Hi John, Hi Jane"
Comments
No comments yet. Be the first to comment!
Please login to leave a comment.