Java Regex: matches(pattern, value) returns true but group() fails to match

后端 未结 2 1345
春和景丽
春和景丽 2020-12-16 15:03

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

相关标签:
2条回答
  • 2020-12-16 15:11

    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:

    • Matcher#find()
    0 讨论(0)
  • 2020-12-16 15:15

    I faced the same issue. Was calling matcher.group(1) WITHOUT checking matcher.find(). Adding if check for matcher.find() solved the problem.

    0 讨论(0)
提交回复
热议问题