java.util.regex.Pattern is a class in Java used to represent a compiled regular expression. It converts a regular expression into a pattern that can be used for matching and searching text. Pattern is commonly used together with the Matcher class for regex operations. It is useful for validation, searching, splitting, and identifying text patterns.
Important Features:
- Creates compiled regular-expression patterns.
- Supports matching and searching operations.
- Works with the
Matcherclass. - Supports regex flags such as case-insensitive matching.
- Can split strings using regular expressions.
- Detects invalid regular-expression syntax.
Syntax:
Pattern pattern = Pattern.compile("regular_expression");
Matcher matcher = pattern.matcher("input");Code language: JavaScript (javascript)
Example to check whether a string contains only digits:
Pattern pattern = Pattern.compile("[0-9]+");
Matcher matcher = pattern.matcher("12345");
System.out.println(matcher.matches());Code language: JavaScript (javascript)
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class PatternDemo {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("[0-9]+");
String input = "12345";
Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
System.out.println("Input contains only digits.");
} else {
System.out.println("Input does not contain only digits.");
}
}
}Output:
Input contains only digits.
Methods of Pattern
Method Signature and Short Description |
|---|
|
|
|
|
|
Splits the given input string around matches of the pattern. |
|
|
|
|
|
|
|
|
|
|
|
|
