1

I'm trying to do a simple regex match but keep running into an IllegalStateException. I've looked at other similar questions with the same issue, and they all say that find() or matches() must first be called before we can use group(). The thing is that I'm already doing that but I'm still getting the exact same exception.

    try
    {
        Pattern p = Pattern.compile(strPattern);
        Matcher m = p.matcher(strInput);

        m.matches();
        m.find();
        System.out.println(m.groupCount()); //returns 9 groups
        System.out.println(m.group(0)); //will crash here
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

Here's the exception I get from this:

 java.lang.IllegalStateException: No match found
   at java.util.regex.Matcher.group(Unknown Source)
   at RegexThing.<init>(RegexThing.java:24)
   at Test.main(Test.java:14)
1
  • 1
    what is the problem? The message is clear "No match found", so m.group(0) doesn't exist. Commented Dec 11, 2014 at 22:07

2 Answers 2

3

You shouldn't call Matcher#matches followed by Matcher#find. The first method will attempt to match the entire input against the pattern. When find executes next, it will attempt to match the next substring that matches the pattern but it will fail to detect any matched pattern because the previous matches has covered the entire input.

Simply call one of them depending on whether you want to match the entire input (matches) or the first subsequence that matches the pattern (find).

You should also print the matched groups only if the match is found:

if(m.find()) {
   System.out.println(m.groupCount()); //returns 9 groups
   System.out.println(m.group(0)); //will crash here
}
Sign up to request clarification or add additional context in comments.

Comments

1

groupCount only returns the number of capturing groups. It says nothing about whether the pattern matched. So you will always get the 9 groups. But m.group(0) throws the exception since the pattern did not match.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.