匹配回归不匹配

时间:2015-10-29 22:14:46

标签: java regex

我在Regex101上测试了我的正则表达式,所有组都被捕获并匹配了我的字符串。但现在当我尝试在java上使用它时,它会返回给我一个

  

java.lang.IllegalStateException:第9行找不到匹配项

   String subjectCode = "02 credits between ----";
   String regex1 = "^(\\d+).*credits between --+.*?$";       
   Pattern p1 = Pattern.compile(regex1);
   Matcher m;

  if(subjectCode.matches(regex1)){
    m = p1.matcher(regex1);
    m.find();
    [LINE 9]Integer subjectCredits = Integer.valueOf(m.group(1));
      System.out.println("Subject Credits: " + subjectCredits);
  }

可能性如何,问题是什么?

1 个答案:

答案 0 :(得分:2)

以下是修复和优化(感谢转到@cricket_007):

String subjectCode = "02 credits between ----";
String regex1 = "(\\d+).*credits between --+.*";
Pattern p1 = Pattern.compile(regex1);
Matcher m = p1.matcher(subjectCode);
if (m.matches()) {
    Integer subjectCredits = Integer.valueOf(m.group(1));
    System.out.println("Subject Credits: " + subjectCredits);
}

您需要将输入字符串传递给matcher。作为次要增强功能,您只需使用1 Matcher#matches,然后在匹配时访问捕获的组。正则表达式不需要^$,因为matches()整个输入应与模式匹配。

请参阅IDEONE demo