使用模式(不是字符串)检查另一个字符串是否与正则表达式匹配

问题描述:

字符串有一个方便的方法matches(String regex)。但是我正要检查大约10-100个匹配值。我不认为让Java为每次调用编译模式都是非常有效的。相反,我想缓存解析的模式并使用它。使用模式(不是字符串)检查另一个字符串是否与正则表达式匹配

但是,我如何尽可能保持有效,使用Pattern对象和字符串来产生boolean,指示字符串匹配模式?

public static boolean patternMatches(String tested, Pattern regex) { 
    ??? 
} 

第二个原因我想做到这一点的是,我已经拥有了采用串并检索文字串配衬方法:

public MyClass[] findMatches(String substring) { 
    ... 
} 

所以我想让过载:

public MyClass[] findMatches(Pattern regex) { 
    ... 
} 
+1

相关:http://*.com/questions/1720191/java-util-regex-importance-of-pattern-compile – Tomalak

+3

你检查[documentation](http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html)?因为如何做你想做的事情就是它展示的第一件事情之一。 – user2357112

+0

@ user2357112不,我检查了关于模式的指南,他们没有提到这种事情。我通过查看'Patter.matches(String,String)'源代码来计算出来。 –

模式有一个方法getMatcher它返回一个描述匹配结果的对象。

Pattern pattern = Pattern.compile("pattern"); 
Matcher matcher = pattern.matcher("Matched string."); 
boolean matches = matcher.matches(); 

因此,我的方法是:

public static boolean patternMatches(String tested, Pattern regex) { 
    return regex.matcher(tested).matches(); 
}