Regex 为什么只在设置断点时匹配正则表达式才起作用?
以下JUnit测试仅在我在matcher行上设置断点时才能正确运行。当正常运行或在没有断点的情况下调试它时,它将失败Regex 为什么只在设置断点时匹配正则表达式才起作用?,regex,eclipse,debugging,junit,breakpoints,Regex,Eclipse,Debugging,Junit,Breakpoints,以下JUnit测试仅在我在matcher行上设置断点时才能正确运行。当正常运行或在没有断点的情况下调试它时,它将失败 public class ParserTest { @Test public void test() { final String s = new Parser().parse("Hello(WORLD)"); } public static class Parser { private static final Pattern pattern = Patter
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,效果很好。您需要在
matcher.group()之前调用它。有时,在调试器中检查代码会导致对象的状态发生更改,因为它会强制对对象进行求值。我怀疑这里正在发生这种情况。您需要在matcher.group()之前调用。有时,在调试器中检查代码会导致对象的状态发生更改,因为它会强制对对象进行求值。我怀疑这里发生了这种情况。因此调试器会自动调用matcher.matches()
?这在调试过程中并没有真正的帮助。@oschrenk通常是toString()引起麻烦。大多数IDEJava调试器调用它来显示局部变量。在调试hibernate延迟加载问题时,这会让我感到不安。因此,调试器会自动调用matcher.matches()
?这在调试过程中并没有真正的帮助。@oschrenk通常是toString()引起麻烦。大多数IDEJava调试器调用它来显示局部变量。在调试hibernate延迟加载问题时,这让我有点头疼。正如@sblundy和@bouzuya指出的,我忘记调用Matcher
对象上的matches()
。问题仍然存在,为什么调试器会计算matcher对象。正如@sblundy和@bouzuya指出的,我忘记调用matcher
对象上的matches()
。但问题仍然存在,为什么调试器将计算matcher对象。
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();
}
}