当我在匹配器行上设置断点时,以下JUnit测试只能正确运行。正常运行或没有断点进行调试时,它将失败。
public class ParserTest {
@Test
public void test() {
final String s = new Parser().parse("Hello(WORLD)");
}
public static class Parser {
private static final Pattern pattern = Pattern
.compile("([a-zA-Z\\s]*)\\(([A-Z]{5,5})\\)");
public String parse(final String raw) {
// put a breakpoint on the matcher in eclipse,
// debug as junit test, then step over
final Matcher matcher = pattern.matcher(raw);
return matcher.group(2) + ":" + matcher.group(1);
}
}
}
抛出以下异常
java.lang.IllegalStateException: No match found
at java.util.regex.Matcher.group(Matcher.java:461)
at lab.ParserTest$Parser.parse(ParserTest.java:22)
at lab.ParserTest.test(ParserTest.java:11)
我创建了一个RegEx Planet Cookbook here,它运行正常。
答案 0 :(得分:2)
您需要在matcher.group()
之前致电matcher.matches()
。有时检查调试器中的代码会导致对象的状态发生变化,因为它会强制要求评估。我怀疑这发生在这里。
答案 1 :(得分:2)
public String parse(final String raw) {
// put a breakpoint on the matcher in eclipse,
// debug as junit test, then step over
final Matcher matcher = pattern.matcher(raw);
if (matcher.matches()) {
return matcher.group(2) + ":" + matcher.group(1);
} else {
throw new IllegalArgumentException();
}
}