PlayMa256
PlayMa256

Reputation: 6831

Matcher returning not match

i'v tested my regex on Regex101 and all the groups was captured and matched my string. But now when i'm trying to use it on java, it returns to me a

java.lang.IllegalStateException: No match found on line 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);
  }

How's that possible and what's the problem?

Upvotes: 0

Views: 75

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626728

Here is a fix and optimizations (thanks go to @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);
}

You need to pass the input string to the matcher. As a minor enhancement, you can use just 1 Matcher#matches and then access the captured group if there is a match. The regex does not need ^ and $ since with matches() the whole input should match the pattern.

See IDEONE demo

Upvotes: 2

Related Questions