java.util.regex Package
The java.util.regex package in Java provides classes for matching character sequences against regular expressions. It allows developers to define complex search patterns and apply them to text for operations such as validation, searching, replacement, and splitting strings.
Package Declaration
Every class that uses regex features should import this package as follows:
import java.util.regex.*;
import java.util.regex.*;
public class GFG {
public static void main(String[] args)
{
// Define a regex pattern for digits
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher
= pattern.matcher("Java 17 and 2025 version");
while (matcher.find()) {
System.out.println("Found number: "
+ matcher.group());
}
}
}
Output
Found number: 17 Found number: 2025
Explanation:
- The regex \\d+ matches one or more digits.
- The Matcher object searches the input string and extracts all matching numeric sequences.
Key Classes Regex Package
1. Pattern Class
The Pattern class is used to compile a regular expression into a pattern object. It is immutable and thread-safe, meaning the same pattern can be safely used by multiple threads.
Syntax:
Pattern pattern = Pattern.compile("regex");
import java.util.regex.*;
public class GFG {
public static void main(String[] args){
// matches one or more digits
String regex = "\\d+";
String input = "Order1234";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
System.out.println("Does input contain digits? "
+ matcher.find());
}
}
Output
Does input contain digits? true
Methods of Pattern classs
- compile(String regex): Compiles the given regular expression into a Pattern
- matcher(CharSequence input): Creates a Matcher to match the given input sequence against the pattern.
- matches(String regex, CharSequence input): Checks if the entire input sequence matches the given regex pattern.
- split(CharSequence input): Splits the input string around matches of the pattern.
2. Matcher Class
The Matcher class is used to perform match operations such as finding, matching, and replacing patterns in text.
Syntax:
Matcher matcher = pattern.matcher(input);
import java.util.regex.*;
public class GFG{
public static void main(String[] args){
String regex = "\\bJava\\b";
String input = "I love Java and Java is powerful.";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
System.out.println("Match found at: " + matcher.start() + " - " + matcher.end());
}
System.out.println("Total Matches: " + count);
}
}
Output
Match found at: 7 - 11 Match found at: 16 - 20 Total Matches: 2
Methods of Matcher classs
- matches(): Attempts to match the entire input sequence against the pattern.
- find(): Finds the next subsequence that matches the pattern.
- group(): Returns the matched subsequence.
- start(): Returns the start index of the matched subsequence.
- end(): Returns the end index of the matched subsequence
- replaceAll(String replacement): Replaces every match with the given replacement string.
- replaceFirst(String replacement): Replaces the first match only.
3. PatternSyntaxException Class
The PatternSyntaxException is thrown when there’s an invalid syntax in the regular expression. It helps identify the error index and description for debugging.
Syntax:
PatternSyntaxException exception = new PatternSyntaxException(description, pattern, index)
import java.util.regex.*;
public class GFG {
public static void main(String[] args){
try{
Pattern pattern = Pattern.compile(
"[a-z"); // Missing closing bracket
}
catch (PatternSyntaxException e) {
System.out.println("Description: "
+ e.getDescription());
System.out.println("Error Index: "
+ e.getIndex());
System.out.println("Invalid Pattern: "
+ e.getPattern());
}
}
}
Output
Description: Unclosed character class Error Index: 3 Invalid Pattern: [a-z
Methods of PatternSyntaxException Class
- getDescription(): Returns a description of the syntax error
- getIndex(): Returns the approximate index where the error occurred.
- getPattern(): Returns the erroneous regex pattern.
- getMessage(): Returns a multi-line string describing the syntax error in detail.
Common Regex Examples
| Purpose | Regex Pattern | Example Input | Matches |
|---|---|---|---|
| Digits only | \\d+ | Order123 | 123 |
| Alphabets only | [a-zA-Z]+ | Hello123 | Hello |
| Email validation | ^[\\w.-]+@[\\w.-]+\\.\\w+$ | user@mail.com | Valid |
| Mobile number (10 digits) | \\d{10} | 9876543210 | Valid |
| Starts with "Java" | ^Java.* | JavaProgramming | Valid |