【发布时间】:2016-05-26 17:28:06
【问题描述】:
为什么下面的代码可以正常工作
Matcher reg = Pattern.compile("(A|B)\\w{2}(C|D)").matcher("");
while ((line=reader.readLine()) != null)
{
if (!loading || reg.reset(line).matches())
{
if (reg.reset(line).matches()) {
String id = reg.group(1);
}
}
}
但是
while ((line=reader.readLine()) != null)
{
if (!loading || reg.reset(line).matches())
{
String id = reg.group(1);
}
}
抛出 IllegalSyntaxException?
我很惊讶,因为我已经在 if 条件中调用了匹配项。期望它返回与组匹配的字符串,而不是抛出异常。
java.lang.IllegalStateException: No match found
我错过了什么?
【问题讨论】:
-
错误说明了一切:- 找不到匹配项
-
看起来
!loading是真的,所以reg.reset(line).matches()甚至不会被执行。 -
loading的值是多少? -
布尔加载为假,但您仍在尝试通过 reg.group(1) 获取匹配项。在第一个代码示例中,您有一个 if 语句来检查是否存在匹配项,在第二个代码示例中,您删除了该 if 语句。
-
@user6188402 不正确。该模式准确定义了可用的组数。实际匹配可能会留下很多
null,但它们仍然存在。此外,如果组不存在,你会得到IndexOutOfBoundsException,而不是IllegalStateException。
标签: java regex pattern-matching matcher