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.Pattern
Used 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.Matcher
Applies 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
Pattern pattern = Pattern.compile("hello");
Matcher matcher = pattern.matcher("hello");
System.out.println(matcher.matches()); // true
2. Find Substring Matches
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher("Order123 and Ref456");
while (matcher.find()) {
System.out.println("Found number: " + matcher.group());
}
3. Extract Groups
String text = "Name: John, Age: 30";
Pattern pattern = Pattern.compile("Name: (\\w+), Age: (\\d+)");
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
System.out.println("Name: " + matcher.group(1));
System.out.println("Age: " + matcher.group(2));
}
4. Replace All
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher("Order 123 and 456");
String result = matcher.replaceAll("###");
System.out.println(result); // "Order ### and ###"
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:
Pattern pattern = Pattern.compile("hello", Pattern.CASE_INSENSITIVE);
4. Utility Methods using Regex (outside Matcher)
String.matches()
boolean valid = "12345".matches("\\d+"); // true
Equivalent to:
Pattern.compile(regex).matcher(input).matches()
String.replaceAll()
String clean = "abc123".replaceAll("\\d", ""); // "abc"
String.split()
String[] parts = "A,B,C".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
Was this helpful?