Java 正则表达式:matches(pattern, value) 返回 true 但 group() 无法匹配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7033082/
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
Java Regex: matches(pattern, value) returns true but group() fails to match
提问by Ready4Android
I have an odd problem with a regular expression in Java. I tested my Regex and my value hereand it works. It says there are 3 groups (correct) the match for the first group (not group zero!) is SSS, the match for group 2 is BB and the match for group 3 is 0000. But my code below fails and I am quite at a loss why...
我对 Java 中的正则表达式有一个奇怪的问题。我在这里测试了我的 Regex 和我的价值,它有效。它说有 3 个组(正确),第一组(不是零组!)的匹配是 SSS,第 2 组的匹配是 BB,第 3 组的匹配是 0000。但我下面的代码失败了,我很在损失为什么...
String pattern = "([^-]*)-([\D]*)([\d]*)";
String value = "SSS-BB0000";
Matcher matcher = Pattern.compile(pattern).matcher(value);
//group() is equivalent to group(0) - it fails to match though
matcher.group();
Here is a screenshot from the matching result of the above website:
下面是上面网站的匹配结果截图:
I'd be really grateful if anyone could point out the mistake I am making... On an additional note: Strangely enough, if I execute the following code true is returned which implies a match should be possible...
如果有人能指出我犯的错误,我将不胜感激……另外一点:奇怪的是,如果我执行以下代码,则返回 true ,这意味着匹配应该是可能的……
//returns true
Pattern.matches(pattern, value);
回答by Jo?o Silva
You need to call find()
before group()
:
你需要调用find()
之前group()
:
String pattern = "([^-]*)-([\D]*)([\d]*)";
String value = "SSS-BB0000";
Matcher matcher = Pattern.compile(pattern).matcher(value);
if (matcher.find()) {
System.out.println(matcher.group()); // SSS-BB0000
System.out.println(matcher.group(0)); // SSS-BB0000
System.out.println(matcher.group(1)); // SSS
System.out.println(matcher.group(2)); // BB
System.out.println(matcher.group(3)); // 0000
}
When you invoke matcher(value)
, you are merely creating a Matcher
object that will be able to match your value
. In order to actually scan the input, you need to use find()
or lookingAt()
:
当您调用时matcher(value)
,您只是在创建一个Matcher
能够匹配您的value
. 为了实际扫描输入,您需要使用find()
或lookingAt()
: