Class Matcher
Pattern against an input sequence.
Drop-in compatible with Matcher. Supports indexed and named
capture group access via group(int), group(String), start(int),
end(int), start(String), and end(String).
Instances are not thread-safe. Create one instance per thread or per match operation.
-
Constructor Summary
ConstructorsConstructorDescriptionMatcher(Pattern pattern, CharSequence input) Creates a newMatcherfor the given pattern and input. -
Method Summary
Modifier and TypeMethodDescriptionappendReplacement(StringBuffer sb, String replacement) Appends the input betweenlastAppendPosandstart()tosb, then appends the processed replacement string.appendReplacement(StringBuilder sb, String replacement) Appends the remaining input fromlastAppendPosto the end of the input tosb.Appends the remaining input fromlastAppendPosto the end of the input tosb.intend()Returns the end index (exclusive) of the previous match.intend(int group) Returns the end index (exclusive) of the subsequence captured by the given group during the previous match operation.intReturns the end index (exclusive) of the subsequence captured by the named group during the previous match operation.booleanfind()Attempts to find the next subsequence of the input sequence that matches the pattern.booleanfind(int start) Resets this matcher and then attempts to find a match starting no earlier than character positionstart.group()Returns the input subsequence matched by the previous match operation.group(int group) Returns the input subsequence captured by the given group during the previous match operation.Returns the input subsequence captured by the named group during the previous match operation.intReturns the number of capturing groups in this matcher's pattern.booleanReturns whether this matcher uses anchoring bounds.booleanhasMatch()Returns whether the last match operation succeeded.booleanReturns whether this matcher uses transparent bounds.booleanhitEnd()Returnstrueif the end of input was hit by the search engine in the last match operation performed by this matcher.booleanAttempts to match the input sequence, starting at the beginning of the region (from), against the pattern.booleanmatches()Attempts to match the entire region against the pattern.Returns an unmodifiable map from named capturing group names to their 1-based indices.static StringReturns a string in which each metacharacter (\and$) insis escaped, producing a replacement string that is treated as entirely literal byappendReplacement(StringBuilder, String),replaceAll(String), andreplaceFirst(String).region(int start, int end) Sets the limits of this matcher's region.intReturns the end (exclusive) of this matcher's region.intReturns the start (inclusive) of this matcher's region.replaceAll(String replacement) Replaces every subsequence of the input sequence that matches the pattern with the given replacement string.replaceAll(Function<MatchResult, String> replacer) Replaces every subsequence of the input that matches the pattern with the string produced by applyingreplacerto eachMatchResult.replaceFirst(String replacement) Resets the matcher, finds the first match, replaces it withreplacement, and returns the result.replaceFirst(Function<MatchResult, String> replacer) Resets the matcher, finds the first match, appliesreplacerto produce a replacement string, and returns the result.reset()Resets this matcher.results()Returns a lazily-evaluated stream of all non-overlapping matches in the input from the current position.intstart()Returns the start index of the previous match.intstart(int group) Returns the start index of the subsequence captured by the given group during the previous match operation.intReturns the start index of the subsequence captured by the named group during the previous match operation.Returns the MatchResult for the last match operation.useAnchoringBounds(boolean b) Sets whether anchors (^,$,\A,\z) treat the region boundaries as the start/end of input.usePattern(Pattern newPattern) Changes the pattern used by this matcher to find matches in the input.useTransparentBounds(boolean b) Sets whether lookahead and lookbehind assertions can see characters outside the region.
-
Constructor Details
-
Matcher
Creates a newMatcherfor the given pattern and input.The initial region covers the full input
[0, input.length()), anchoring bounds are enabled, and transparent bounds are disabled — matching JDK defaults.- Parameters:
pattern- the compiled pattern; must not be nullinput- the character sequence to match; must not be null
-
-
Method Details
-
matches
public boolean matches()Attempts to match the entire region against the pattern.- Returns:
- true if the entire region matches
-
find
public boolean find()Attempts to find the next subsequence of the input sequence that matches the pattern.After a zero-length match the search position is advanced by one character so that subsequent calls do not return the same zero-length match and so that the method terminates. This matches the behaviour of
Matcher.find().- Returns:
- true if a subsequent match is found
-
find
public boolean find(int start) Resets this matcher and then attempts to find a match starting no earlier than character positionstart.Performs a full reset (equivalent to calling
reset()) before beginning the search. The search starts at positionstartwithin the input and proceeds forward. After a zero-length match the search position is advanced by one character.After a successful call, invoking
find()continues the search from where this call left off.- Parameters:
start- the character index at which to begin the search; must be in[0, input.length()]- Returns:
- true if a match is found starting at or after
start - Throws:
IndexOutOfBoundsException- ifstart < 0orstart > input.length()
-
lookingAt
public boolean lookingAt()Attempts to match the input sequence, starting at the beginning of the region (from), against the pattern.Unlike
matches(), the entire region does not need to match; the pattern must only match a prefix of the region starting exactly atfrom. Unlikefind(), the match must start atfromexactly.This method does not modify
from,to,lastAppendPos, orfindFromStart. A subsequentfind()call will resume from whateverfromwas before this call.After a successful return,
group(),start(),end(), and group accessors all work as after a successfulfind()ormatches().- Returns:
- true if the pattern matches a prefix of the region starting at
from
-
reset
Resets this matcher. The region is restored to[0, input.length()),anchoringBoundsis set totrue, andtransparentBoundsis set tofalse— matching JDKreset()semantics.- Returns:
- this matcher
-
region
Sets the limits of this matcher's region.All subsequent match operations search only within
[start, end)of the full input. The search cursor is reset tostart, and all previous match state is cleared. The anchoring and transparent bounds flags are not changed.- Parameters:
start- the inclusive start of the new region; must satisfy0 <= start <= input.length()end- the exclusive end of the new region; must satisfystart <= end <= input.length()- Returns:
- this matcher
- Throws:
IndexOutOfBoundsException- if any bound is outside the valid range
-
regionStart
public int regionStart()Returns the start (inclusive) of this matcher's region.- Returns:
- the region start;
0by default
-
regionEnd
public int regionEnd()Returns the end (exclusive) of this matcher's region.- Returns:
- the region end;
input.length()by default
-
useAnchoringBounds
Sets whether anchors (^,$,\A,\z) treat the region boundaries as the start/end of input.When
bistrue(the default), anchors are evaluated relative to the current region. Whenfalse, anchors are evaluated against the full input string.- Parameters:
b-trueto enable anchoring bounds,falseto disable- Returns:
- this matcher
-
hasAnchoringBounds
public boolean hasAnchoringBounds()Returns whether this matcher uses anchoring bounds.- Returns:
trueif anchoring bounds are enabled;trueby default
-
useTransparentBounds
Sets whether lookahead and lookbehind assertions can see characters outside the region.When
bisfalse(the default), lookahead is blocked atregionEndand lookbehind is blocked atregionStart. Whentrue, assertions see the full input.- Parameters:
b-trueto enable transparent bounds,falseto disable- Returns:
- this matcher
-
hasTransparentBounds
public boolean hasTransparentBounds()Returns whether this matcher uses transparent bounds.- Returns:
trueif transparent bounds are enabled;falseby default
-
hitEnd
public boolean hitEnd()Returnstrueif the end of input was hit by the search engine in the last match operation performed by this matcher.Returns
truewhen:- the last operation was
matches()(any result — the engine always spans[from, to]); - the last operation returned
trueand the match end equals the region boundaryto(more input could extend the match); or - the last operation returned
falseand the engine scanned input up to the region boundary before concluding no match exists (more input could produce one).
Returns
falsewhen:- no match operation has been performed since the last
reset(); - the last operation returned
trueand the match end is strictly inside the region (more input cannot change the found match); or - the last operation returned
falseand the engine determined no match was possible without reaching the region end — for example, a start-anchored pattern like^abcapplied to"xyz"fails at position 0.
- Returns:
trueif the end of input was hit during the last operation
- the last operation was
-
hasMatch
public boolean hasMatch()Returns whether the last match operation succeeded.Returns false if no match has been attempted or the last attempt failed. Mirrors Java 21's
MatchResult.hasMatch().- Returns:
- true if the last find or matches call found a match
-
start
public int start()Returns the start index of the previous match.- Returns:
- the start index
- Throws:
IllegalStateException- if no match has been attempted yet
-
end
public int end()Returns the end index (exclusive) of the previous match.- Returns:
- the end index
- Throws:
IllegalStateException- if no match has been attempted yet
-
start
public int start(int group) Returns the start index of the subsequence captured by the given group during the previous match operation.- Parameters:
group- the 1-based capturing group index; 0 returns the match start- Returns:
- the start index of the captured group, or -1 if the group did not match
- Throws:
IllegalStateException- if no match has been attempted or no match foundIndexOutOfBoundsException- ifgroupis out of range
-
end
public int end(int group) Returns the end index (exclusive) of the subsequence captured by the given group during the previous match operation.- Parameters:
group- the 1-based capturing group index; 0 returns the match end- Returns:
- the end index (exclusive) of the captured group, or -1 if the group did not match
- Throws:
IllegalStateException- if no match has been attempted or no match foundIndexOutOfBoundsException- ifgroupis out of range
-
group
Returns the input subsequence matched by the previous match operation.- Returns:
- the matched subsequence; never null
- Throws:
IllegalStateException- if no match has been attempted yet
-
group
Returns the input subsequence captured by the given group during the previous match operation.- Parameters:
group- the 1-based group index; 0 returns the whole match- Returns:
- the captured substring, or null if the group did not participate in the match
- Throws:
IllegalStateException- if no match has been performed or no match foundIndexOutOfBoundsException- ifgroupis out of range
-
group
Returns the input subsequence captured by the named group during the previous match operation.- Parameters:
name- the capturing group name; must not be null- Returns:
- the captured substring, or null if the group did not participate in the match
- Throws:
IllegalStateException- if no match has been performed or no match foundIllegalArgumentException- ifnamedoes not correspond to a named group
-
start
Returns the start index of the subsequence captured by the named group during the previous match operation.- Parameters:
name- the capturing group name; must not be null- Returns:
- the start index of the named group, or -1 if the group did not participate
- Throws:
IllegalStateException- if no match has been performed or no match foundIllegalArgumentException- ifnamedoes not correspond to a named group
-
end
Returns the end index (exclusive) of the subsequence captured by the named group during the previous match operation.- Parameters:
name- the capturing group name; must not be null- Returns:
- the end index (exclusive) of the named group, or -1 if the group did not participate
- Throws:
IllegalStateException- if no match has been performed or no match foundIllegalArgumentException- ifnamedoes not correspond to a named group
-
groupCount
public int groupCount()Returns the number of capturing groups in this matcher's pattern.This value is determined solely by the compiled pattern and does not depend on whether a match has been found. This mirrors the contract of
java.util.regex.Matcher#groupCount().- Returns:
- the number of capturing groups; zero if the pattern has none
-
namedGroups
Returns an unmodifiable map from named capturing group names to their 1-based indices.Derived from the pattern's metadata. Returns an empty map if the pattern has no named groups.
- Returns:
- an unmodifiable map of group name to 1-based index; never null
-
usePattern
Changes the pattern used by this matcher to find matches in the input.This is a partial reset. The last match result is discarded and the append position is reset to zero. The input, the current region (
regionStart,regionEnd), the region bounds flags (anchoringBounds,transparentBounds), the current search cursor (from), and the last-match-end position (lastMatchEnd) are all preserved. The nextfind()call continues from wherever the cursor was.This matches the contract of
java.util.regex.Matcher#usePattern(Pattern).- Parameters:
newPattern- the new pattern; must not be null- Returns:
- this matcher
- Throws:
NullPointerException- ifnewPatternis null
-
replaceAll
Replaces every subsequence of the input sequence that matches the pattern with the given replacement string.Resets the matcher before searching, mirroring JDK semantics.
- Parameters:
replacement- the replacement string; must not be null- Returns:
- the resulting string with all matches replaced
- Throws:
NullPointerException- ifreplacementis null
-
replaceAll
Replaces every subsequence of the input that matches the pattern with the string produced by applyingreplacerto eachMatchResult.Resets the matcher before searching, mirroring JDK semantics.
- Parameters:
replacer- a function mapping each match result to a replacement string; must not be null- Returns:
- the resulting string with all matches replaced
- Throws:
NullPointerException- ifreplaceris null
-
replaceFirst
Resets the matcher, finds the first match, replaces it withreplacement, and returns the result. Returns the input unchanged if no match is found.- Parameters:
replacement- the replacement string; must not be null- Returns:
- the resulting string with the first match replaced, or the original input if no match
- Throws:
NullPointerException- ifreplacementis null
-
replaceFirst
Resets the matcher, finds the first match, appliesreplacerto produce a replacement string, and returns the result. Returns the input unchanged if no match.- Parameters:
replacer- a function mapping the match result to a replacement string; must not be null- Returns:
- the resulting string with the first match replaced, or the original input if no match
- Throws:
NullPointerException- ifreplaceris null
-
appendReplacement
Appends the input betweenlastAppendPosandstart()tosb, then appendsreplacement. AdvanceslastAppendPostoend().Intended for use in a loop with
appendTail(StringBuilder).- Parameters:
sb- the string builder to append to; must not be nullreplacement- the replacement string to append; must not be null- Returns:
- this matcher
- Throws:
NullPointerException- ifsborreplacementis nullIllegalStateException- if no match has been found
-
appendReplacement
Appends the input betweenlastAppendPosandstart()tosb, then appends the processed replacement string. AdvanceslastAppendPostoend().Group references (
$1,${name}) and escape sequences (\\,\$) in the replacement are expanded byapplyReplacement(String).- Parameters:
sb- the string buffer to append to; must not be nullreplacement- the replacement string; must not be null- Returns:
- this matcher
- Throws:
NullPointerException- ifsborreplacementis nullIllegalStateException- if no match has been foundIllegalArgumentException- ifreplacementcontains an illegal group reference syntaxIndexOutOfBoundsException- ifreplacementreferences a group that does not exist
-
appendTail
Appends the remaining input fromlastAppendPosto the end of the input tosb.- Parameters:
sb- the string builder to append to; must not be null- Returns:
sb- Throws:
NullPointerException- ifsbis null
-
appendTail
Appends the remaining input fromlastAppendPosto the end of the input tosb.- Parameters:
sb- the string buffer to append to; must not be null- Returns:
sb- Throws:
NullPointerException- ifsbis null
-
quoteReplacement
Returns a string in which each metacharacter (\and$) insis escaped, producing a replacement string that is treated as entirely literal byappendReplacement(StringBuilder, String),replaceAll(String), andreplaceFirst(String).This is the inverse of
applyReplacement(String)for pure-literal input:applyReplacement(quoteReplacement(s))returnssfor any stringsand any match state.This method is a static utility and has no effect on matcher state.
- Parameters:
s- the string to quote; must not be null- Returns:
- the quoted string; never null
- Throws:
NullPointerException- ifsis null
-
results
Returns a lazily-evaluated stream of all non-overlapping matches in the input from the current position.Resets the matcher first to ensure consistent behaviour, then produces one
MatchResultsnapshot per match. The stream terminates whenfind()returns false.- Returns:
- a stream of match results; never null
-
toMatchResult
Returns the MatchResult for the last match operation.The returned snapshot is immutable: subsequent find/matches calls do not affect it. Groups 0 through
groupCount()are accessible viastart(n),end(n), andgroup(n).If no match has been attempted, the returned result reports
hasMatch() == falseand all start/end/group accessors return-1ornull. This mirrors the behaviour ofjava.util.regex.Matcher#toMatchResult()in Java 20+.- Returns:
- an immutable
MatchResult; never null
-