我正在尝试进行简单的正则表达式匹配,但一直遇到 IllegalStateException。我看过其他有相同问题的类似问题,他们都说必须先调用 find() 或 matches() 才能使用 group()。问题是我已经这样做了,但我仍然遇到完全相同的异常。
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();
}
这是我从中得到的异常:
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)
最佳答案
您不应该在调用 Matcher#matches
后调用 Matcher#find
。第一种方法将尝试将整个输入与模式匹配。当接下来执行 find
时,它会尝试匹配下一个与该模式匹配的子字符串,但它将无法检测到任何匹配的模式,因为之前的 matches
已经覆盖了 整个输入。
根据您是要匹配整个输入(matches
)还是匹配模式的第一个子序列(find
),只需调用其中一个即可。
您还应该仅在找到匹配项时打印匹配的组:
if(m.find()) {
System.out.println(m.groupCount()); //returns 9 groups
System.out.println(m.group(0)); //will crash here
}
关于带有正则表达式的 Java IllegalStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27433285/