【问题标题】:Why does matching the RegEx only work when setting a breakpoint?为什么匹配 RegEx 仅在设置断点时才有效?
【发布时间】:2012-01-14 01:43:35
【问题描述】:

只有当我在匹配行上设置断点时,以下 JUnit 测试才会正确运行。正常运行或者无断点调试都会失败。

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 here,它运行良好。

【问题讨论】:

  • 正如@sblundy 和@bouzuya 指出的那样,我忘记在Matcher 对象上调用matches()。问题仍然存在,为什么调试器会评估匹配器对象。

标签: regex eclipse debugging junit breakpoints


【解决方案1】:

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

【讨论】:

  • 所以调试器会自动调用matcher.matches()?这在调试过程中并没有真正的帮助。
  • @oschrenk 通常是 toString() 引起麻烦。大多数 IDE java 调试器调用它来显示局部变量。在调试hibernate延迟加载问题时,这让我很痛苦。
【解决方案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();
        }
    }

【讨论】:

    猜你喜欢
    • 2010-09-29
    • 2014-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    • 2012-08-21
    • 1970-01-01
    • 2017-11-12
    相关资源
    最近更新 更多