2012-01-14 2 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); 
    } 
} 
} 

다음 예외가 나는 정규식 행성 요리 책 here을 만들

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) 

을 던져 그것을 잘 작동합니다.

+0

그래서 @sblundy와 @bouzuya는 Matcher 객체에서'matches()'를 호출하는 것을 잊어 버렸습니다. 디버거가 matcher 객체를 평가하는 이유는 무엇입니까? – oschrenk

답변

2

matcher.matches()matcher.group() 전에 전화해야합니다. 때로는 디버거에서 코드를 검사하면 물건을 평가하도록 강제하기 때문에 객체의 상태가 변경됩니다. 나는 그것이 여기에서 일어나고 있다고 생각한다.

+0

디버거가 자동으로'matcher.matches()'를 호출합니까? 디버깅 프로세스에는 도움이되지 않습니다. – oschrenk

+0

@oschrenk 일반적으로 문제를 일으키는 것은 toString()입니다. 대부분의 IDE java 디버거는이를 호출하여 로컬 변수를 표시합니다. 이것은 최대 절전 모드의 게으른 로딩 문제를 디버깅 할 때 약간 시간이 걸린다. – sblundy

+0

그건 의미가 있습니다. 소스 코드를 살펴 보겠습니다. – oschrenk

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

관련 문제