Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: why do we get Matcher from Pattern

Tags:

java

regex

Why did java developers did the way we get matcher from pattern? I mean why

Matcher matcher=pattern.matcher(string)

I think logically there must be something like

Pattern pattern=Pattern.compile(pattern);
Matcher matcher=new Matcher(pattern,string);
//if we need
matcher.setPattern(newPattern);

I mean a matcher is like an regex engine and pattern is like commands for this engine. Why do we create engine from commands?


1 Answers

The implementation of the pattern matching algorithm needs to keep track of certain state variables.

Since Pattern represents a threadsafe object it cannot itself contain these variables (else it would not be threadsafe), therefore these variables are stored in a matcher object which is created for a single match call and which is not threadsafe. From the Pattern Javadoc:

Instances of this class are immutable and are safe for use by multiple concurrent threads. Instances of the Matcher class are not safe for such use.

Additionally the Matcher class also provides access to match results like match groups etc.

like image 67
wero Avatar answered Dec 06 '25 09:12

wero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!