Java regex: matches (pattern, value) returns true, but group () cannot match

I have a strange problem with regular expressions in Java I tested my regular expression and my value here, how it works It says there are three groups (correct) the first group (not group zero!) The match of is SSS, the match of group 2 is BB, and the match of group 3 is 0000 But my code failed below. I'm quite 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();

The following is a screenshot of the matching results of the above websites:

I would appreciate it if someone could point out the error I'm doing... Another note: strangely, if I execute the following code, it returns true, which means that matching should be possible

//returns true
Pattern.matches(pattern,value);

Solution

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 call matcher (value), you just create a matcher object that matches your value In order to actually scan the input, you need to use find() or lookingat():

reference:

> Matcher#find()

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>