Java Regex:matches(pattern,value)返回true但group()无法匹配 [英] Java Regex: matches(pattern, value) returns true but group() fails to match
问题描述
我在Java中使用正则表达式有一个奇怪的问题。我测试了我的正则表达式和我的价值
I have an odd problem with a regular expression in Java. I tested my Regex and my value here and 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...
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...
//returns true
Pattern.matches(pattern, value);
You need to call find()
before 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()
:
References:
这篇关于Java Regex:matches(pattern,value)返回true但group()无法匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!