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

import java.util.regex.Pattern;

// 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

Matcher matcher = pattern.matcher("aaaab");

matches(String regex, CharSequence input)

A static method that directly determines whether the input string completely 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, 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

// Case-insensitive matching
Pattern pattern = Pattern.compile("a*b", Pattern.CASE_INSENSITIVE);

Practical Applications of the Pattern Class

Validating Email Format

Example

String emailRegex = "^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$";
Pattern emailPattern = Pattern.compile(emailRegex);

String email = "test@example.com";
boolean isValid = emailPattern.matcher(email).matches();

Extracting 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"
}

Replacing 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 Tips

  1. Precompile regular expressions: For regular expressions that need to be used multiple times, they should be precompiled into anPatternobject rather than recompiled each time they are used.

  2. Avoid overly complex regular expressions: Overly complex regular expressions may lead to performance degradation, or even "catastrophic backtracking" issues.

  3. 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
Other Extensions