Java Regex Matching: matches, find, Groups and Named Groups
Put Java regular expressions to work with Pattern and Matcher: matches, lookingAt and find, predicates for streams, iterating with find and results(), Scanner.findAll, numbered and named groups, namedGroups, MatchResult snapshots, regions and \G.
kvi5hnuCode Sprout team member9 min readOn this page
Article 36 covered the pattern language. Now we use it. There are two basic tasks: deciding whether a string has a required shape (validation), and locating the parts of a string that match (searching and extraction). Both go through two classes:
Patternis a compiled regular expression. It's immutable and thread-safe, so compile it once and keep it in astatic finalfield.Matcherapplies a pattern to one input and keeps track of the current match. It's mutable and not thread-safe. Create one per input, which is cheap.
Testing a match
For a one-off test, the static method is enough:
if (Pattern.matches("-?\\d+", input)) ...
It compiles the pattern every time, though. String.matches(regex) does the same. When the same regex is used repeatedly, compile it once:
private static final Pattern INTEGER = Pattern.compile("-?\\d+");
Matcher m = INTEGER.matcher(input); // input is any CharSequence
if (m.matches()) ...
A matcher offers three ways to test:
| Method | Succeeds when |
|---|---|
matches() | the entire input matches |
lookingAt() | a prefix of the input matches |
find() | the pattern matches somewhere after the previous match |
matches and lookingAt always start at the beginning. find continues where the last match ended. That's what makes the loops below work, but it also means that calling find after a successful matches on the same matcher searches only the rest of the input. find(int start) resets the matcher and searches from the given index, and reset() starts over. Since Java 20, hasMatch() tells you whether the matcher currently holds a match, without changing its state.
Patterns as predicates
Two methods turn a pattern into a Predicate<String> that works with streams and collections:
asMatchPredicate()(Java 11) tests that the whole string matches.asPredicate()(Java 8) tests that the string contains a match.
Pattern digits = Pattern.compile("[0-9]+");
words.stream().filter(digits.asMatchPredicate()) // "1999"
words.stream().filter(digits.asPredicate()) // "31st", "1999"
Finding all matches
The classic loop calls find until it returns false:
Matcher m = pattern.matcher(input);
while (m.find()) {
String match = m.group();
int start = m.start(); // index of the first character
int end = m.end(); // index after the last character
}
results() (Java 9) gives the same matches as a Stream<MatchResult>. MatchResult is an interface with group, start and end. Matcher implements it, and the stream's elements are immutable snapshots.
List<String> numbers = pattern.matcher(input).results().map(MatchResult::group).toList();
For text in a file, Scanner.findAll produces the same kind of stream without reading the whole file into a string first:
try (var in = new Scanner(path, StandardCharsets.UTF_8)) {
List<String> words = in.findAll("\\pL+").map(MatchResult::group).toList();
}
When an empty match is possible (\d*, for instance), the matcher still advances by at least one character after each one, so the loop always ends.
Groups
Capturing groups let you take a match apart. Suppose a line item from an invoice looks like this:
Blackwell Toaster USD29.95
and the pattern is
(\p{Alnum}+(\s+\p{Alnum}+)*)\s+([A-Z]{3})([0-9.]*)
After a successful matches, find or lookingAt, group(n) returns the text of group n, and start(n) and end(n) give its position. Groups are numbered by their opening parenthesis from the left, starting at 1. Group 0 is the whole match. groupCount() returns the number of groups, not counting group 0.
if (m.matches()) {
String item = m.group(1); // "Blackwell Toaster"
String currency = m.group(3); // "USD"
String price = m.group(4); // "29.95"
}
Some details matter:
- A group that didn't take part in the match, like an optional
(?:\.(\d+))?that was skipped, hasgroup(n) == nullandstart(n) == -1. - A group inside a repetition remembers only its last iteration. In
(\w)+onabc, group 1 isc. To get every iteration, wrap the whole repetition in its own group, or use a separatefindloop for the repeated part. - Calling
group()when there's no current match throwsIllegalStateException. Always check the result ofmatchesorfindfirst.
Non-capturing and named groups
Group 2 above exists only because the repetition needed parentheses. Turn it into (?:...) and the numbering gets simpler. Better yet, name the groups you care about:
(?<item>\p{Alnum}+(?:\s+\p{Alnum}+)*)\s+(?<currency>[A-Z]{3})(?<price>[0-9.]*)
String item = m.group("item");
int itemEnd = m.end("item");
Named groups are still numbered too, so group(1) and group("item") are the same here. Pattern.namedGroups() returns the map from names to numbers. Since Java 20, MatchResult also has group(String), start(String), end(String) and namedGroups(), so named groups work on the snapshots from results() and on toMatchResult().
Readable patterns
Complex patterns are easier to read with the COMMENTS flag (or (?x) inside the pattern). Then whitespace in the pattern is ignored, and # starts a comment that runs to the end of the line. Text blocks fit this style well:
Pattern time = Pattern.compile("""
([1-9]|1[0-2]) # hours
:([0-5][0-9]) # minutes
[ap]m""", Pattern.COMMENTS);
In this mode, a literal space or # must be escaped in the regex as \ or \# (or written as \x20); in a Java string literal or text block that's \\ and \\#. Unlike in Perl, putting them in a character class doesn't help: Java ignores whitespace and comments inside classes too (a[ ]b fails with Unclosed character class).
Snapshots, regions and anchoring
toMatchResult()copies the current match into an immutableMatchResult. Use it when you want to store matches, because the matcher's own state changes on the nextfind.region(start, end)limits matching to part of the input, without creating a substring.^,$,lookingAtandmatchesthen refer to the region's bounds.useAnchoringBounds(false)anduseTransparentBounds(true)change how anchors and lookaround treat the region edges.\Gmatches where the previous match ended.\G(\d)in afindloop picks up consecutive digits from the start and stops at the first gap.hitEnd()reports whether the last match attempt reached the end of the input. That's useful when you scan incomplete input and need to know whether more characters could change the result.usePattern(p)switches to another pattern while keeping the position, which is handy for small hand-written tokenizers.
The program
The demo tests the three match methods, filters a list with predicates, extracts phone numbers, links from an HTML snippet and words from a temporary file, then takes the invoice line apart with numbered and named groups. Group boundaries are drawn as parentheses, as in ((11):(59))am.
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.util.regex.*;
public class Solution {
/** Show group boundaries with parentheses, like ((11):(59))am. */
static String showGroups(Matcher m, String input) {
var sb = new StringBuilder();
int g = m.groupCount();
for (int i = 0; i <= input.length(); i++) {
for (int j = g; j >= 1; j--) // close inner groups first
if (m.end(j) == i && m.start(j) != i) sb.append(')');
for (int j = 1; j <= g; j++)
if (m.start(j) == i && m.end(j) == i) sb.append("()");
for (int j = 1; j <= g; j++)
if (m.start(j) == i && m.end(j) != i) sb.append('(');
if (i < input.length()) sb.append(input.charAt(i));
}
return sb.toString();
}
public static void main(String[] args) throws IOException {
System.out.println("--- matches, lookingAt, find ---");
Pattern integer = Pattern.compile("-?\\d+");
for (String s : List.of("-42", "42 apples", "apples: 42")) {
System.out.printf("%-12s matches=%-5b lookingAt=%-5b find=%b%n", '"' + s + '"',
integer.matcher(s).matches(), integer.matcher(s).lookingAt(), integer.matcher(s).find());
}
Matcher reused = integer.matcher("-42");
System.out.println("same matcher: matches=" + reused.matches() + ", then find=" + reused.find()
+ ", find(0)=" + reused.find(0));
System.out.println("Pattern.matches: " + Pattern.matches("[a-z]+", "regex"));
Matcher fresh = integer.matcher("7");
System.out.println("hasMatch before/after find: " + fresh.hasMatch() + " " + (fresh.find() && fresh.hasMatch()));
System.out.println("--- predicates ---");
Pattern digits = Pattern.compile("[0-9]+");
var words = List.of("December", "31st", "1999");
System.out.println("asMatchPredicate: " + words.stream().filter(digits.asMatchPredicate()).toList());
System.out.println("asPredicate: " + words.stream().filter(digits.asPredicate()).toList());
System.out.println("--- all matches ---");
String text = "Call 555-1234 or 555-9876, not 12-34.";
Matcher phone = Pattern.compile("\\d{3}-\\d{4}").matcher(text);
while (phone.find())
System.out.println("found " + phone.group() + " at [" + phone.start() + ", " + phone.end() + ")");
List<String> all = Pattern.compile("\\d+").matcher(text).results().map(MatchResult::group).toList();
System.out.println("results(): " + all);
String html = """
<p>See <a href="https://openjdk.org">OpenJDK</a> and <A HREF='docs.html'>docs</A>
or <a class="x" href=plain.html>this</a>.</p>""";
Pattern href = Pattern.compile("<a\\s[^>]*?href\\s*=\\s*(\"[^\"]*\"|'[^']*'|[^\\s>]+)[^>]*>",
Pattern.CASE_INSENSITIVE);
href.matcher(html).results().map(r -> r.group(1)).forEach(h -> System.out.println("link " + h));
Path file = Files.createTempFile("words", ".txt");
Files.writeString(file, "Les naïfs Ärger\nüber 3 Dinge", StandardCharsets.UTF_8);
try (var in = new Scanner(file, StandardCharsets.UTF_8)) {
System.out.println("Scanner.findAll: " + in.findAll("\\pL+").map(MatchResult::group).toList());
} finally {
Files.delete(file);
}
System.out.println("--- groups ---");
Pattern item = Pattern.compile("(\\p{Alnum}+(\\s+\\p{Alnum}+)*)\\s+([A-Z]{3})([0-9.]*)");
String line = "Blackwell Toaster USD29.95";
Matcher m = item.matcher(line);
if (m.matches()) {
System.out.println("groupCount " + m.groupCount());
for (int i = 0; i <= m.groupCount(); i++)
System.out.printf("group %d = \"%s\" [%d, %d)%n", i, m.group(i), m.start(i), m.end(i));
}
Pattern named = Pattern.compile(
"(?<item>\\p{Alnum}+(?:\\s+\\p{Alnum}+)*)\\s+(?<currency>[A-Z]{3})(?<price>[0-9.]*)");
m = named.matcher(line);
if (m.matches())
System.out.println("item=" + m.group("item") + ", currency=" + m.group("currency")
+ ", price=" + new java.math.BigDecimal(m.group("price")) + ", item ends at " + m.end("item"));
System.out.println("namedGroups: " + new TreeMap<>(named.namedGroups()));
Matcher opt = Pattern.compile("(\\d+)(?:\\.(\\d+))?").matcher("42");
if (opt.matches()) System.out.println("unmatched optional group: " + opt.group(2) + ", start " + opt.start(2));
Matcher rep = Pattern.compile("(\\w)+").matcher("abc");
if (rep.matches()) System.out.println("repeated group keeps only the last: " + rep.group(1));
var time = Pattern.compile("""
([1-9]|1[0-2]) # hours
:([0-5][0-9]) # minutes
[ap]m""", Pattern.COMMENTS);
String t = "11:59am";
Matcher tm = time.matcher(t);
if (tm.matches()) System.out.println("commented pattern: " + showGroups(tm, t));
Matcher nested = Pattern.compile("((1?[0-9]):([0-5][0-9]))[ap]m").matcher(t);
if (nested.matches()) System.out.println("nested groups: " + showGroups(nested, t));
System.out.println("--- MatchResult snapshots and regions ---");
Matcher w = Pattern.compile("\\w+").matcher("one two three");
var snapshots = new ArrayList<MatchResult>();
while (w.find()) snapshots.add(w.toMatchResult());
System.out.println("snapshots: " + snapshots.stream().map(r -> r.group() + "@" + r.start()).toList());
w.reset().region(4, 13);
System.out.println("in region [4, 13): " + (w.lookingAt() ? w.group() : "-"));
Matcher g = Pattern.compile("\\G(\\d)").matcher("123x45");
var leading = new StringBuilder();
while (g.find()) leading.append(g.group(1));
System.out.println("\\G stops at the first gap: " + leading);
try {
Pattern.compile("x").matcher("y").group();
} catch (IllegalStateException e) {
System.out.println("group() without a match: " + e.getMessage());
}
}
}
--- matches, lookingAt, find ---
"-42" matches=true lookingAt=true find=true
"42 apples" matches=false lookingAt=true find=true
"apples: 42" matches=false lookingAt=false find=true
same matcher: matches=true, then find=false, find(0)=true
Pattern.matches: true
hasMatch before/after find: false true
--- predicates ---
asMatchPredicate: [1999]
asPredicate: [31st, 1999]
--- all matches ---
found 555-1234 at [5, 13)
found 555-9876 at [17, 25)
results(): [555, 1234, 555, 9876, 12, 34]
link "https://openjdk.org"
link 'docs.html'
link plain.html
Scanner.findAll: [Les, naïfs, Ärger, über, Dinge]
--- groups ---
groupCount 4
group 0 = "Blackwell Toaster USD29.95" [0, 29)
group 1 = "Blackwell Toaster" [0, 17)
group 2 = " Toaster" [9, 17)
group 3 = "USD" [21, 24)
group 4 = "29.95" [24, 29)
item=Blackwell Toaster, currency=USD, price=29.95, item ends at 17
namedGroups: {currency=2, item=1, price=3}
unmatched optional group: null, start -1
repeated group keeps only the last: c
commented pattern: (11):(59)am
nested groups: ((11):(59))am
--- MatchResult snapshots and regions ---
snapshots: [one@0, two@4, three@8]
in region [4, 13): two
\G stops at the first gap: 123
group() without a match: No match found
Notice that \d{3}-\d{4} doesn't find 12-34, and that \d+ finds every run of digits, including those inside phone numbers. The link pattern accepts double-quoted, single-quoted and unquoted attribute values, upper or lower case. Even so, regular expressions are fine for quick extraction from HTML you know, but not for parsing arbitrary HTML or XML. Part 3 of this course covers real XML parsers.
Common questions
How do I extract all numbers from a string?
Pattern.compile("-?\\d+(?:\\.\\d+)?").matcher(text).results().map(MatchResult::group).toList() gives the numbers as strings; add .map(Double::parseDouble) to convert them.
Is String.matches bad practice?
It is fine for occasional checks. In a loop or a frequently called method, it recompiles the pattern each time, so keep a static final Pattern and call pattern.matcher(s).matches() or use asMatchPredicate() instead.
Why does matches() return false when find() finds the text?
matches requires the entire input to match the pattern; find looks for the pattern anywhere. For a "contains" test use find, or wrap the pattern in .* for matches, which is slower and clumsier.
Can I share a Matcher between threads?
No, a matcher holds the state of one ongoing search. Share the Pattern, which is immutable and thread-safe, and create a matcher per input and thread.
How do I get both the match and its position?
m.group(), m.start() and m.end() inside the find loop, or r.start() and r.end() on each MatchResult from results(). end is the index after the match, so the matched text is input.substring(start, end).
API reference
| API | Purpose |
|---|---|
Pattern.compile(regex), compile(regex, flags) | compile a pattern |
Pattern.matcher(input) | create a matcher for a CharSequence |
Pattern.matches(regex, input) | compile and test a whole input once |
Pattern.asPredicate() / asMatchPredicate() | predicate for "contains a match" / "matches entirely" |
Pattern.namedGroups() | map from group names to numbers (Java 20) |
Matcher.matches(), lookingAt(), find(), find(start) | test the whole input, a prefix, or search |
Matcher.hasMatch() | whether there's a current match (Java 20) |
Matcher.results() | stream of all remaining matches as MatchResult (Java 9) |
Matcher.group(), group(n), group(name) | text of the match or of a group; null if the group didn't participate |
Matcher.start(..), end(..) | position of the match or a group; -1 if the group didn't participate |
Matcher.groupCount() | number of capturing groups |
Matcher.toMatchResult() | immutable snapshot of the current match |
Matcher.reset(), reset(input) | start over, optionally with new input |
Matcher.region(start, end) | restrict matching to part of the input |
Matcher.hitEnd(), usePattern(p) | end-of-input detection, change of pattern |
Scanner.findAll(pattern) | stream of matches from a scanner's input (Java 9) |
Summary
- Compile a
Patternonce and reuse it, since it's thread-safe. Create a newMatcherfor each input. matchesneeds the whole input to match,lookingAta prefix, andfindsearches from the end of the previous match.asMatchPredicateandasPredicateplug patterns into streams.- Loop with
while (m.find()), or useresults()for a stream ofMatchResults.Scanner.findAlldoes the same for files. - Groups are numbered by their opening parenthesis. Group 0 is the whole match, unmatched groups give
nulland -1, and repeated groups keep their last iteration. - Named groups
(?<name>...)make extraction readable, andCOMMENTSmode makes long patterns readable.
Practice Questions
What do matches, lookingAt and find return for the pattern \d+ and the input 2024 was a leap year?
Each on a fresh matcher: matches() is false, because the whole input isn't digits. lookingAt() is true, because the input starts with 2024. find() is true and finds 2024. Called again on the same matcher, find() would return false, since there are no more digit runs. (On a single matcher, a find() right after the successful lookingAt() would also return false, because it continues after 2024.)
Write code that collects all hashtags (a # followed by letters or digits) from a post into a list of tag names without the #.
Pattern.compile("#([\\p{L}\\p{N}]+)").matcher(post).results().map(r -> r.group(1)).toList(). The group captures the name without the #, and results() delivers each match as a MatchResult.
In (\d+)(?:\.(\d+))? applied with matches() to "42", what are groupCount(), group(1) and group(2)?
groupCount() is 2, because the non-capturing group isn't counted. group(1) is "42". group(2) is null, because the optional part didn't participate, and start(2) is -1.
Why is it a bug to store the Matcher itself in a list of found matches inside a find loop?
The matcher is one mutable object whose state changes with every find. All list entries would be the same object, describing only the latest match, or no match at all after the loop ends. Store m.toMatchResult() or the extracted strings instead, or use results(), which already produces snapshots.
A Pattern is stored in a static field and used by many threads. Is that safe? What about a Matcher?
A Pattern is immutable and safe to share among threads, and sharing it avoids recompiling. A Matcher holds per-match state and isn't thread-safe. Each thread, or each input, should call pattern.matcher(input) to get its own matcher.
Previous: Java Regular Expressions: Syntax, Character Classes and Quantifiers
Next: Java Regex Split, Replace and Flags: splitWithDelimiters, replaceAll and Pattern Flags
Related reading
- Java Regular Expressions: Syntax, Character Classes and Quantifiers
- Java Serialization: readResolve, writeReplace, Versioning and Security
- Customizing Java Serialization: transient, readObject, writeObject and Externalizable
- The Java Serialization File Format: Handles, Class Descriptors and Fingerprints
- Java Object Serialization: Saving and Loading Objects

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.