2012-01-14 37 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

相關問題