Java中的regex重用模式实例
我的问题是,当与String.matches( )
一起使用时,是否可以使用Pattern.compile( )
重用已编译的模式
因为文件上说
A
matches
method is defined by this class as a convenience for when a regular expression is used just once. This method compiles an expression and matches an input sequence against it in a single invocation. The statementboolean b = Pattern.matches("a*b", "aaaaab");
is equivalent to the three statements above, though for repeated matches it is less efficient since it does not allow the compiled pattern to be reused.
http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html
它只是说,当你使用模式。这样效率就会降低。我对这一部分感到困惑:
An invocation of this method of the form
str.matches(regex)
yields exactly the same result as the expressionPattern.matches(regex, str)
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#matches(java.lang.String)
因此,我不确定String.matches
是否使用Pattern.matches
,因此我无法再次重用编译后的模式。我实际上计划将编译后的模式设置为常量(出于优化目的)
# 1 楼答案
Pattern.matches()
方法是一种静态方法,因此如果要重用已编译的模式,就不能使用它。编译模式是Pattern
类的实例Pattern.matches()
每次使用正则表达式时都编译它您可以通过存储
Pattern
类的实例来重用已编译的模式,例如:然后,每次你想使用它的时候,你都可以得到一个匹配器