Pattern.matcher()到底如何工作?

时间:2018-06-25 01:57:11

标签: java regex parsing pattern-matching matcher

因此,我正在尝试创建一个与字符串的某些部分匹配的解析器。字符串看起来像f(q [group1],[group2])=(q [group3],[group4],[group5])。下面代码中的Pattern.matches()返回true,但是我无法通过matcher.group(int)访问组。提供的代码的最后一行抛出:java.lang.IllegalStateException:没有匹配项

public class Parser {
   Pattern pattern;
   Matcher matcher;
   String g;

public Parser(String s) {
   g = s.replaceAll("\\s+", "");
   pattern = Pattern.compile("^f\\(q(\\d+),(.)\\)=\\(q([+-]*\\d+),(.),([+-])1\\)$");
   matcher = pattern.matcher(g);
   boolean b = Pattern.matches("^f\\(q(\\d+),(.)\\)=\\(q([+-]*\\d+),(.),([+-])1\\)$",g);

 System.out.println(b +   " ");
 System.out.println(matcher.group(1));
}
}

1 个答案:

答案 0 :(得分:0)

您从未与匹配者匹配任何内容。我不确定为什么要调用静态方法Pattern.matches,但该行应显示为

boolean b = matcher.matches();

赞:

public class Parser {
    Pattern pattern;
    Matcher matcher;
    String g;

    public Parser(String s) {
        g = s.replaceAll("\\s+", "");
        pattern = Pattern.compile("^f\\(q(\\d+),(.)\\)=\\(q([+-]*\\d+),(.),([+-])1\\)$");
        matcher = pattern.matcher(g);
        boolean b = matcher.matches();

        System.out.println(b + " ");
        System.out.println(matcher.group(1));
    }
}