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
Regex:
\\d{3}-\\d{3}-\\d{4}
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 and lookbehind are zero-width assertions that allow you to match patterns based on what comes before or after a string without consuming characters.
Lookahead (
(?=...)): Ensures a match is followed by a specific pattern.Negative Lookahead (
(?!...)): Ensures a match is not followed by a specific pattern.Lookbehind (
(?<=...)): Ensures a match is preceded by a specific pattern.Negative Lookbehind (
(?<!...)): Ensures a match is not preceded by a specific pattern.
Lookahead Example
Match a word that is followed by a specific pattern (e.g., match the word "apple" only if it’s followed by "pie").
Negative Lookahead Example
Match the word "apple" only if it is not followed by "pie".
Lookbehind Example
Match a word that is preceded by a specific pattern (e.g., match "pie" only if it is preceded by "apple").
Negative Lookbehind Example
Match "pie" only if it is not preceded by "apple".
Capturing Groups
Capturing groups allow us to extract specific portions of a matched string.
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.
We can name capturing groups for easier access.
Nested Capturing Groups to extract first and last names from full name
Match a full name and extract first and last names.
Replacing Text
The Matcher.replaceAll() and Matcher.replaceFirst() methods allow us to replace matched text in the input string.
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
Using replaceAll() with a function, we can conditionally transform the text.
Practical Use Cases
1. Validating Email Addresses
A common use case is validating whether an email address is in a valid format.
2. Parsing URLs
Extract different components from a URL, such as the protocol, domain, and path.
3. Data Extraction from Logs
Extract specific error codes from log files.
4. Extracting Dates from Text
Find and extract all dates from a text that follow the pattern MM-DD-YYYY.
Output:
Last updated