qiubit
qiubit

Reputation: 4816

Java - Matcher throws IllegalStateException after accessing group

I'm trying to write simple command parser class for my project. Here's what I have:

Main.java

public static void main(String[] args) {
    CmdParser p = new CmdParser(args);
    String st = p.getSourceType();
}

CmdParser.java

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CmdParser {

    private String[] args;

    public CmdParser(String[] args) {
        this.args = args;
    }

    public String getSourceType() throws ParseException {
        ArrayList<String> sourceTypes = new ArrayList<String>();
        Pattern p = Pattern.compile("--source-type=([^\\s]+)");
        for (String s : args) {
            Matcher m = p.matcher(s);
            if (m.groupCount() == 1) {
                sourceTypes.add(m.group(1)); //line 28
            }
        }
        return sourceTypes.get(0);
    }
}

Running this with java Main --source-type=test causes the following output:

Exception in thread "main" java.lang.IllegalStateException: No match found
    at java.util.regex.Matcher.group(Matcher.java:536)
    at CmdParser.getSourceType(CmdParser.java:28)
    at Main.main(Main.java:11)

I commented line 28 above. How is that possible that even though groupCount is 1, so that should be a correct group index, java throws IllegalStateException in this case? Also, why is pattern not found?

Upvotes: 1

Views: 1356

Answers (2)

karthik manchala
karthik manchala

Reputation: 13640

You have to call m.find() before m.group():

for (String s : args) {
        Matcher m = p.matcher(s);
        if (m.find()) {
            sourceTypes.add(m.group(1)); //line 28
        }
    }

Upvotes: 2

anubhava
anubhava

Reputation: 785246

You need to use:

if (m.find() && m.groupCount() == 1) {
    sourceTypes.add(m.group(1)); //line 28
}

i.e. call find or matches before group() method.

Upvotes: 2

Related Questions