2012-01-14 32 views
1

当我在匹配器行上设置断点时,以下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并能正常工作。

+0

所以@sblundy和@bouzuya指出,我忘了在Matcher对象上调用'matches()'。问题仍然存在,为什么调试器会评估匹配器对象。 – oschrenk 2012-01-14 02:26:01

回答

2

您需要在matcher.group()之前致电matcher.matches()。有时在调试器中检查代码会导致对象的状态发生变化,因为它会强制评估。我怀疑这发生在这里。

+0

所以调试器自动调用'matcher.matches()'?这在调试过程中并没有什么帮助。 – oschrenk 2012-01-14 02:24:17

+0

@oschrenk它通常是导致问题的toString()。大多数IDE Java调试器调用它来显示局部变量。在调试休眠延迟加载问题时,这有点让我苦恼几次。 – sblundy 2012-01-14 02:38:02

+0

这很有道理。我会看看源代码。 – oschrenk 2012-01-14 02:54:39

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(); 
     } 
    } 
+0

好的。这是理解的。但为什么它会在调试器中工作? – oschrenk 2012-01-14 02:21:33

相关问题