Learn about Regular Expressions (RegEx) in Java and how to use them for pattern matching, validation, and text processing. Regular expressions provide a powerful way to search, extract, and manipulate text based on patterns.
Regular expressions (RegEx) are sequences of characters that define a search pattern. They are used for pattern matching within text and are supported in most programming languages, including Java.
Here are some common patterns used in regular expressions:
\d
- Matches any digit (0-9)\w
- Matches any word character (alphanumeric plus underscore)\s
- Matches any whitespace character (spaces, tabs, line breaks).
- Matches any character except newline*
- Matches 0 or more of the preceding element+
- Matches 1 or more of the preceding element?
- Matches 0 or 1 of the preceding element{n}
- Matches exactly n occurrences of the preceding element{n,}
- Matches n or more occurrences of the preceding element{n,m}
- Matches between n and m occurrences of the preceding elementCapture groups allow you to extract parts of the matched text:
(pattern)
- Creates a capture group with the matched pattern(?<name>pattern)
- Creates a named capture groupHere's how you might use RegEx in Java for various common tasks:
// Simple pattern matching String text = "Java Regular Expressions"; boolean matches = text.matches(".*Regular.*"); // true // Finding all matches in a string String text = "Contact us at support@example.com or sales@example.com"; Pattern pattern = Pattern.compile("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}"); Matcher matcher = pattern.matcher(text); while (matcher.find()) { System.out.println("Found email: " + matcher.group()); } // Using capture groups to extract data String dateString = "Today is 2023-05-15"; Pattern pattern = Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})"); Matcher matcher = pattern.matcher(dateString); if (matcher.find()) { String year = matcher.group(1); // 2023 String month = matcher.group(2); // 05 String day = matcher.group(3); // 15 System.out.println("Year: " + year + ", Month: " + month + ", Day: " + day); } // Using named capture groups String nameString = "John Doe"; Pattern pattern = Pattern.compile("(?<firstName>\\w+)\\s(?<lastName>\\w+)"); Matcher matcher = pattern.matcher(nameString); if (matcher.find()) { String firstName = matcher.group("firstName"); // John String lastName = matcher.group("lastName"); // Doe System.out.println("First name: " + firstName + ", Last name: " + lastName); }