Java - 匹配器在访问组后抛出 IllegalStateException

标签 java regex

我正在尝试为我的项目编写简单的命令解析器类。这是我拥有的:

主.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);
    }
}

使用 java Main --source-type=test 运行它会导致以下输出:

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)

我评论了上面的第 28 行。即使 groupCount 为 1,那怎么可能是正确的组索引,在这种情况下 java 会抛出 IllegalStateException?另外,为什么找不到模式?

最佳答案

你需要使用:

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

即在 group() 方法之前调用 findmatches

关于Java - 匹配器在访问组后抛出 IllegalStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30581103/

相关文章:

javascript - 使用 jQuery 删除 HTML 元素之间的空格和换行符

regex - Flutter TextField inputFormatters 无法使用我的自定义正则表达式

java - 无法将 CSV 值解析为 Double

java - 为什么 Hive 和 HiveServer2 需要 mapred.InputFormat?

java - SOLR 7+/Lucene 7+ 以及 DelegatingCollector 和 PostFilter 的性能问题

java - 创建多个文件的 Netbeans 模板

java - 正则表达式在比赛后获得 n 行

java - 在 Mirth 中处理消息时出现内存不足错误

Java 正则表达式模式在 Linux (Amazon Beanstalk) 下不起作用

javascript - 如果满足某些条件,是否有更好的方法将空格后的最后一个字符串替换为另一个字符串?