user928112
user928112

Reputation: 582

Java IllegalStateException with regex

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)

Upvotes: 1

Views: 306

Answers (2)

dan b
dan b

Reputation: 1182

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.

Upvotes: 1

M A
M A

Reputation: 72854

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
}

Upvotes: 3

Related Questions