The following JUnit test will only run correctly for me when I set a breakpoint on the matcher line. When running it normally or debugging it without a breakpoint it will fail.
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);
}
}
}
The following exception is thrown
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)
I create a RegEx Planet Cookbook here and it works fine.
You need to call
matcher.matches()beforematcher.group(). Sometimes examining code in a debugger cause the state of an object to change because it forces things to evaluate. I suspect that’s happening here.