本文介绍了java.util.regex.Pattern可以进行部分匹配吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以知道流/字符串是否包含 匹配正则表达式的输入。
Is it possible to know if a stream/string contains an input that could match a regular expression.
例如
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()
方法查明是否有更长的字符串匹配:
Yes, Java provides a way to do that. First you have to call one of the standard methods to apply the regex, like matches()
or find()
. If that returns false
, you can use the hitEnd()
method to find out if some longer string could have matched:
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.util.regex.Pattern可以进行部分匹配吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!