How to find matches with a regular expression
Short answer
Compile the pattern into a Pattern, create a Matcher for the text and call find():
void main() {
Matcher matcher = Pattern.compile("#\\w+").matcher("Learning #java and #regex today");
while (matcher.find()) {
IO.println(matcher.group());
}
}Output:
#java
#regexGroups
Parentheses create groups — parts of the match you can get by number:
void main() {
Matcher matcher = Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})").matcher("Due: 2026-03-15");
if (matcher.find()) {
IO.println("year " + matcher.group(1) + ", month " + matcher.group(2));
}
}Output:
year 2026, month 03Named groups
A group name (?<name>...) makes the code clearer than numbers:
void main() {
var pattern = Pattern.compile("(?<key>\\w+)=(?<value>\\w+)");
pattern.matcher("host=localhost port=8080").results()
.forEach(m -> IO.println(m.group("key") + " -> " + m.group("value")));
}Output:
host -> localhost
port -> 8080results() returns MatchResult objects. They support named groups since Java 20.
Replacing with groups
In the replacement string $1, $2 refer to groups:
void main() {
IO.println("2026-03-15".replaceAll("(\\d{4})-(\\d{2})-(\\d{2})", "$3.$2.$1"));
}Output:
15.03.2026Common mistake
Using matches() to look for part of the text. matches() requires the whole string to match, while find() searches inside it:
void main() {
Matcher matcher = Pattern.compile("\\d+").matcher("room 42");
IO.println(matcher.matches());
IO.println(matcher.reset().find());
}Output:
false
trueFunctions used in this recipe
- Pattern.compile() — Compiles a regular expression into a Pattern object that can be reused many times.
- Matcher.find() — Searches for the next match of the pattern anywhere in the string.
- String.matches() — Checks whether the whole string matches a regular expression.
- String.replaceAll() — Replaces every match of a regular expression.