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?


You need to use:

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

ie call find or matches before group() method.


你必须在m.group()之前调用m.find() m.group()

for (String s : args) {
        Matcher m = p.matcher(s);
        if (m.find()) {
            sourceTypes.add(m.group(1)); //line 28
        }
    }
链接地址: http://www.djcxy.com/p/30576.html

上一篇: Java正则表达式匹配IllegalStateException

下一篇: Matcher在访问组之后抛出IllegalStateException