0

the following block of code is producing a "No match found" error, despite online resources computing that the regular expression is a match to the String from Scanner "scnr." If anyone can give a short code fix with minimal changes, that would be great.

String p = "([0-9]*),([0-9]*),(r|b)";

System.out.println("regex: " + p);
Pattern pattern = Pattern.compile(p);
Matcher matcher;

String testString = scnr.next();
System.out.println("test string: " + testString);
matcher = pattern.matcher(testString);

matcher.matches();

System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
System.out.println(matcher.group(3));



Output:

regex: ([0-9]*),([0-9]*),(r|b)
test string: (1,65,b)
Exception in thread "main" java.lang.IllegalStateException: No match found

2 Answers2

0

You need to use Matcher#find instead of Matcher#matches which attempts to match the entire region against the pattern.

Do it as follows:

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String p = "([0-9]*),([0-9]*),(r|b)";
        Scanner scnr = new Scanner(System.in);
        System.out.println("regex: " + p);
        Pattern pattern = Pattern.compile(p);
        Matcher matcher;
        System.out.print("Test string: ");
        String testString = scnr.next();
        matcher = pattern.matcher(testString);
        if (matcher.find()) {
            System.out.println(matcher.group(1) + "\t" + matcher.group(2) + "\t" + matcher.group(3));
        }
    }
}

A sample run:

regex: ([0-9]*),([0-9]*),(r|b)
Test string: (1,65,b)
1   65  b
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
0

You were trying to match the string against the whole pattern but it wont work since you have multiple groups.

Pattern pattern = Pattern.compile("([0-9]*),([0-9]*),([rb])");
    String testString = scnr.next();
    System.out.println("test string: " + testString);
    Matcher matcher  = pattern.matcher(testString);

    while (matcher.find()) {
        System.out.println(matcher.group(1));
        System.out.println(matcher.group(2));
        System.out.println(matcher.group(3));
    }
letMeThink
  • 81
  • 1
  • 8