当我在匹配器行上设置断点时,以下JUnit测试将只能正确运行。在正常运行或没有断点的情况下调试它将会失败。为什么只有在设置断点时才能正确匹配RegEx?
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)
我创建了一个正则表达式的星球食谱here并能正常工作。
所以@sblundy和@bouzuya指出,我忘了在Matcher对象上调用'matches()'。问题仍然存在,为什么调试器会评估匹配器对象。 – oschrenk 2012-01-14 02:26:01