Java Pattern Class
Java Date Class Pattern class is one of the core components of regex functionality; it belongs to the java.util.regex the package.
A regular expression (Regular Expression) is a powerful text processing tool used to match, find, and replace specific patterns in strings.
Pattern The main role of the class is to compile a regular expression into a pattern (Pattern) for efficient matching operations afterward.
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
Pattern The class has no public constructor and must be created through the static method compile() to create an instance:
Example
import
java.util.regex.Pattern
;
// Compile the regular expression
Pattern pattern
=
Pattern.
compile
(
"a*b"
)
;
// 2022-01-01 00:00:00 GMT
matcher(CharSequence input)
Create a Matcher object, used to perform matching operations on the input string:
Example
Matcher matcher
=
pattern.
matcher
(
"aaaab"
)
;
matches(String regex, CharSequence input)
A static method that directly determines whether the input string fully matches the regular expression:
Example
boolean
isMatch
=
Pattern.
matches
(
"a*b"
,
"aaaab"
)
;
// Returns true
split(CharSequence input)
Splits the input string according to the regular expression:
Example
String
[
]
parts
=
pattern.
split
(
"aaaabtest"
)
;
// Returns ["", "test"]
Regular expression flags
When compiling a regular expression, you can specify different flags to change the matching behavior:
| Flag | Description |
|---|---|
Pattern.CASE_INSENSITIVE |
Case-insensitive |
Pattern.MULTILINE |
Multiline mode,^ and $ matches the beginning and end of each line |
Pattern.DOTALL |
. Matches all characters, including line breaks |
Pattern.UNICODE_CASE |
Enables Unicode-aware case folding |
Usage example:
Example
// Case-insensitive matching
Pattern pattern
=
Pattern.
compile
(
"a*b"
, Pattern.
CASE_INSENSITIVE
)
;
Practical applications of the Pattern class
Validate email format
Example
String
emailRegex
=
"^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$"
;
Pattern emailPattern
=
Pattern.
compile
(
emailRegex
)
;
String
=
"test@example.com"
;
boolean
isValid
=
emailPattern.
matcher
(
)
.
matches
(
)
;
Extract numbers
Example
String
text
=
"Price: $123.45"
;
Pattern numberPattern
=
Pattern.
compile
(
"\d+\.?\d*"
)
;
Matcher matcher
=
numberPattern.
matcher
(
text
)
;
if
(
matcher.
find
(
)
)
{
String
number
=
matcher.
group
(
)
;
// "123.45"
}
Replace strings
Example
String
input
=
"Hello, my phone is 123-456-7890"
;
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 Suggestions
-
Precompile regular expressions: For regular expressions that need to be used multiple times, they should be precompiled into a
Patternobject rather than recompiled each time they are used. -
Avoid overly complex regular expressions: Overly complex regular expressions may cause performance degradation, or even the "catastrophic backtracking" problem.
-
Use groups appropriately: Non-capturing groups
(?:...)perform better than capturing groups(...); if you do not need to capture content, you should use non-capturing groups.
Summary
Pattern The class is the core of Java's regex functionality, providing powerful string pattern matching capabilities. Through reasonable use of the Pattern class and its companion Matcher class, you can efficiently complete various string processing tasks. Mastering regular expressions and the Pattern class usage will greatly improve a developer's text processing capabilities.
The following table lists the Pattern common methods of the class:
Construction and compilation methods
| Method | Description |
|---|---|
static Pattern compile(String regex) |
Compiles a regular expression into a Pattern object |
static Pattern compile(String regex, int flags) |
Compiles a regular expression with the specified flags |
static boolean matches(String regex, CharSequence input) |
Quickly matches a regular expression (compile + match) |
static String quote(String s) |
Converts a string into a literal pattern (escaping all special characters) |
Flag constants (common)
| Flag | Description |
|---|---|
Pattern.CASE_INSENSITIVE |
Case-insensitive matching |
Pattern.MULTILINE |
Multiline mode (^ and $ match line start and end) |
Pattern.DOTALL |
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 using the pattern |
String[] split(CharSequence input, int limit) |
Splits with a limited number of times |
Stream |
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 |