Java Pattern Class
In Java,Patternthe class is one of the core components of regular expression functionality; it belongs to thejava.util.regexpackage.
Regular Expression is a powerful text processing tool used to match, find, and replace specific patterns in strings.
PatternThe main function of the class is to compile a regular expression into a pattern for efficient matching operations later.
Introduction to Regular Expressions
A regular expression is a syntax used to describe string patterns. Through specific symbols and rules, complex string matching rules can be defined. For example:
\dMatches any digit (equivalent to[0-9])\wMatches any letter, digit, or underscore (equivalent to[a-zA-Z0-9_])a+Matches one or more consecutive lettersa^Matches the beginning of a string$Matches the end of a string
Basic Usage of the Pattern Class
Creating a Pattern Object
PatternThe class has no public constructor; it must be created through the static methodcompile()to create an instance:
Example
// Compile the regular expression
Pattern pattern = Pattern.compile("a*b");
Common Methods
matcher(CharSequence input)
Creates aMatcherobject, used to perform matching operations on an input string:
Example
matches(String regex, CharSequence input)
A static method that directly determines whether the input string completely matches the regular expression:
Example
split(CharSequence input)
Splits the input string according to the regular expression:
Example
Regular Expression Flags
When compiling a regular expression, different flags can be specified to change matching behavior:
| Flag | Description |
|---|---|
Pattern.CASE_INSENSITIVE |
Ignore case |
Pattern.MULTILINE |
Multiline mode,^and$matches the beginning and end of each line |
Pattern.DOTALL |
.Matches all characters, including line terminators |
Pattern.UNICODE_CASE |
Enables Unicode-aware case folding |
Usage example:
Example
Pattern pattern = Pattern.compile("a*b", Pattern.CASE_INSENSITIVE);
Practical Applications of the Pattern Class
Validating Email Format
Example
Pattern emailPattern = Pattern.compile(emailRegex);
String email = "[email protected]";
boolean isValid = emailPattern.matcher(email).matches();
Extracting Numbers
Example
Pattern numberPattern = Pattern.compile("\\d+\\.?\\d*");
Matcher matcher = numberPattern.matcher(text);
if (matcher.find()) {
String number = matcher.group(); // "123.45"
}
Replacing Strings
Example
Pattern phonePattern = Pattern.compile("\\d{3}-\\d{3}-\\d{4}");
String output = phonePattern.matcher(input).replaceAll("[PHONE]");
// Output: "Hello, my phone is [PHONE]"
Performance Optimization Tips
Precompile regular expressions: For regular expressions that need to be used multiple times, they should be precompiled into an
Patternobject rather than recompiled each time they are used.Avoid overly complex regular expressions: Overly complex regular expressions may lead to performance degradation, or even "catastrophic backtracking" issues.
Use groups wisely: Non-capturing groups
(?:...)perform better than capturing groups(...)If you don't need to capture content, use non-capturing groups.
Summary
PatternThe class is the core of Java's regular expression functionality, providing powerful string pattern matching capabilities. Through proper use of thePatternclass and its companionMatcherclass, various string processing tasks can be efficiently completed. Mastering regular expressions and thePatternuse of the class will greatly enhance developers' text processing capabilities.
The following table listsPatternthe common methods of the class:
Construction and Compilation Methods
| Method | Description |
|---|---|
static Pattern compile(String regex) |
Compiles the regular expression into a Pattern object |
static Pattern compile(String regex, int flags) |
Compiles the regular expression with the specified flags |
static boolean matches(String regex, CharSequence input) |
Quickly matches the regular expression (compile + match) |
static String quote(String s) |
Converts the string to a literal pattern (escapes all special characters) |
Flag Constants (Common)
| Flag | Description |
|---|---|
Pattern.CASE_INSENSITIVE |
Case-insensitive matching |
Pattern.MULTILINE |
Multiline mode (^ and $ match the beginning and end of lines) |
Pattern.DOTALL |
The dot (.) matches all characters, including line terminators |
Pattern.UNICODE_CASE |
Enables Unicode-aware case folding |
Matching and Splitting Methods
| Method | Description |
|---|---|
Matcher matcher(CharSequence input) |
Creates a matcher object |
String[] split(CharSequence input) |
Splits the input string with the pattern |
String[] split(CharSequence input, int limit) |
Splitting with a limit |
Stream<String> splitAsStream(CharSequence input) |
Returns the split stream (Java 8+) |
Pattern Information Methods
| Method | Description |
|---|---|
String pattern() |
Returns the compiled regular expression |
int flags() |
Returns the flags set at compile time |
String toString() |
Returns the string representation of the pattern |