java.util.regex.Pattern可以进行部分匹配吗?
是否可以知道流/字符串是否包含可以匹配正则表达式的输入。
例如
String input="AA"; Pattern pat=Pattern.compile("AAAAAB"); Matcher matcher=pat.matcher(input); //<-- something here returning true ?
要么
String input="BB"; Pattern pat=Pattern.compile("AAAAAB"); Matcher matcher=pat.matcher(input); //<-- something here returning false ?
谢谢
是的,Java提供了一种方法。 首先,您必须调用一种标准方法来应用正则表达式,如matches()
或find()
。 如果返回false
,则可以使用hitEnd()
方法查明是否有更长的字符串匹配:
String[] inputs = { "AA", "BB" }; Pattern p = Pattern.compile("AAAAAB"); Matcher m = p.matcher(""); for (String s : inputs) { m.reset(s); System.out.printf("%s -- full match: %B; partial match: %B%n", s, m.matches(), m.hitEnd()); }
输出:
AA -- full match: FALSE; partial match: TRUE BB -- full match: FALSE; partial match: FALSE
实际上,你很幸运:Java的正则表达式确实有你想要的方法:
public boolean hitEnd()
如果在此匹配器执行的最后一个匹配操作中搜索引擎命中输入结尾,则返回true。
当此方法返回true时,更多输入可能会更改上次搜索的结果。
所以在你的情况下:
String input="AA"; Pattern pat=Pattern.compile("AAB"); Matcher matcher=pat.matcher(input); System.out.println(matcher.matches()); // prints "false" System.out.println(matcher.hitEnd()); // prints "true"
hitEnd的替代方法是在RE本身中指定需求。
// Accepts up to 5 'A's or 5 'A's and a 'B' (and anything following) Pattern pat = Pattern.compile("^(?:A{1,5}$|A{5}B)"); boolean yes = pat.matcher("AA").find(); boolean no = pat.matcher("BB").find();
Matcher.matches()不能做你想要的吗?
如果您只想检查字符串是否包含正则表达式指定的某种模式:
String s = ...; s.matches( regex )