java.util.regex.Pattern 可以进行部分匹配吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2526756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can java.util.regex.Pattern do partial matches?
提问by Pierre
Is it possible to know if a stream/string contains an input that couldmatch a regular expression.
是否可以知道流/字符串是否包含可以匹配正则表达式的输入。
For example
例如
String input="AA";
Pattern pat=Pattern.compile("AAAAAB");
Matcher matcher=pat.matcher(input);
//<-- something here returning true ?
or
或者
String input="BB";
Pattern pat=Pattern.compile("AAAAAB");
Matcher matcher=pat.matcher(input);
//<-- something here returning false ?
Thanks
谢谢
回答by Alan Moore
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:
是的,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());
}
output:
输出:
AA -- full match: FALSE; partial match: TRUE
BB -- full match: FALSE; partial match: FALSE
回答by polygenelubricants
Actually, you are in luck: Java's regex does have the method you want:
实际上,您很幸运:Java 的正则表达式确实有您想要的方法:
Returns true if the end of input was hit by the search engine in the last match operation performed by this matcher.
When this method returns true, then it is possible that more input would have changed the result of the last search.
如果在此匹配器执行的最后一次匹配操作中搜索引擎命中了输入的结尾,则返回 true。
当此方法返回 true 时,更多输入可能会更改上次搜索的结果。
So in your case:
所以在你的情况下:
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"
回答by nicerobot
An alternative to hitEnd is to specify the requirement in the RE itself.
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();
回答by Brian Agnew
Does Matcher.matches()not do what you want ?
不Matcher.matches()不是你想要做什么?
回答by Manuel Darveau
If you just want to check if a string contains some pattern specified by a regex:
如果您只想检查字符串是否包含由正则表达式指定的某种模式:
String s = ...;
s.matches( regex )

