Core Classes
About
Regex (Regular Expressions) is a declarative syntax for matching patterns in strings. In Java, regex support is provided in the java.util.regex package, which includes two key classes:
Pattern– represents the compiled regex expressionMatcher– applies the pattern to a given input string
These classes offer robust methods to match, extract, validate, and transform strings based on specific patterns.
1. Class: java.util.regex.Pattern
java.util.regex.PatternUsed to compile a regex string into a Pattern object that can be reused for matching against multiple inputs.
Common Methods
compile(String regex)
Compiles a regular expression
compile(String regex, flags)
Compiles regex with modifiers (e.g., case-insensitive)
matcher(CharSequence input)
Returns a Matcher for input
split(CharSequence input)
Splits a string using the pattern
splitAsStream(CharSequence)
Splits string and returns a stream (Java 8+)
pattern()
Returns the regex string used to compile the pattern
Example:
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher("Order 123 shipped on 2024-06-21");2. Class: java.util.regex.Matcher
java.util.regex.MatcherApplies a Pattern to a specific input and provides methods to check matches, extract groups, and replace content.
Common Methods
matches()
Returns true if entire input matches pattern
find()
Returns true if any subsequence matches pattern
group()
Returns the last matched group
group(int)
Returns specific capturing group
start()
Start index of current match
end()
End index of current match
replaceAll(String)
Replaces all matches with given replacement
replaceFirst(String)
Replaces first match
lookingAt()
Returns true if beginning of input matches pattern
reset()
Resets matcher for a new input
Key Concepts
matches() vs find() vs lookingAt()
matches() vs find() vs lookingAt()matches()
Checks if the entire string matches the pattern
find()
Finds next matching subsequence
lookingAt()
Checks if the start of the string matches
Examples
1. Check Full Match
2. Find Substring Matches
3. Extract Groups
4. Replace All
3. Flags (Modifiers)
Pattern.compile(regex, flag) allows you to control behavior.
(?i)
Pattern.CASE_INSENSITIVE
Ignore case
(?m)
Pattern.MULTILINE
^ and $ match line start/end
(?s)
Pattern.DOTALL
. matches newlines
(?x)
Pattern.COMMENTS
Ignore whitespace in pattern
Example:
4. Utility Methods using Regex (outside Matcher)
String.matches()
Equivalent to:
Pattern.compile(regex).matcher(input).matches()
String.replaceAll()
String.split()
Common Use Cases in String Processing
Validate input
Pattern.matcher().matches()
Extract values
Matcher.find() and group()
Sanitize text
String.replaceAll()
Search in logs
Files.lines().filter(line -> line.matches())
Conditional parsing
Use groups for logic-based extraction
Masking sensitive data
replaceAll("password=.*", "password=***")
Last updated