是否可以知道流/字符串是否包含可以匹配正则表达式的输入.
例如
String input="AA";
Pattern pat=Pattern.compile("AAAAAB");
Matcher matcher=pat.matcher(input);
//<-- something here returning true ?
Run Code Online (Sandbox Code Playgroud)
要么
String input="BB";
Pattern pat=Pattern.compile("AAAAAB");
Matcher matcher=pat.matcher(input);
//<-- something here returning false ?
Run Code Online (Sandbox Code Playgroud)
谢谢
Ala*_*ore 12
是的,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());
}
Run Code Online (Sandbox Code Playgroud)
输出:
AA -- full match: FALSE; partial match: TRUE
BB -- full match: FALSE; partial match: FALSE
Run Code Online (Sandbox Code Playgroud)
实际上,你很幸运:Java的正则表达式确实有你想要的方法:
如果在此匹配器执行的最后一个匹配操作中搜索引擎命中了输入的结尾,则返回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"
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11594 次 |
最近记录: |