當我在匹配器行上設置斷點時,以下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