为什么 Java 开发人员采用我们从模式中获取匹配器的方式?我是说为什么
Matcher matcher=pattern.matcher(string)
我认为逻辑上一定有类似的东西
Pattern pattern=Pattern.compile(pattern);
Matcher matcher=new Matcher(pattern,string);
//if we need
matcher.setPattern(newPattern);
我的意思是匹配器就像一个正则表达式引擎,模式就像这个引擎的命令。为什么我们从命令创建引擎?
最佳答案
模式匹配算法的实现需要跟踪某些状态变量。
由于 Pattern
表示一个线程安全对象,它本身不能包含这些变量(否则它就不是线程安全的),因此这些变量存储在为单个匹配调用创建的匹配器对象中不是线程安全的。来自 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.
此外,Matcher
类还提供对匹配结果(如匹配组等)的访问。
关于Java:为什么我们从 Pattern 中获取 Matcher,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32954061/