【问题标题】:Regex matches in myregexp.com, but not matching in Java正则表达式在 myregexp.com 中匹配,但在 Java 中不匹配
【发布时间】:2014-07-08 09:08:04
【问题描述】:

这是查找会话 ID 的正则表达式:"(?DEEP. [1-9 ] s))”,输出为:

ID 类型 USER IDLE 63494 ABC 深 3 秒 -> 70403 ABC 深 0 秒 82446 ABC DEEOP 52 分 27 秒

在 myregexp.com/signedJar.html 中,这个正则表达式可以正常工作。但是当我尝试使用 Java 查找时,它无法获得输出。请找到sn-p:

    FrameworkControls.regularExpressionPattern = Pattern.compile("(?<=( ))([0-9]*)(?=(.*ABC.*DEEP.*[1-9] s))");
    String deepak = "\n" +
            "\n" +
            "    ID     TYPE    USER                            IDLE\n" +
            "\n" +
            "    63494  ABC     DEEP                            3 s\n" +
            " -> 70403  ABC     DEEAP                           0 s\n" +
            "    82446  ABC     DEEOP                           52 min 27 s\n";

    FrameworkControls.regularExpressionMatcher = FrameworkControls.regularExpressionPattern.matcher(deepak);


    if (FrameworkControls.regularExpressionMatcher.find()) {
        String h = FrameworkControls.regularExpressionMatcher.group().trim();
        System.err.println(h);
    }

“FrameworkControls.regularExpressionMatcher.find()”返回真。但 h 变量始终为空。谁能告诉我,我可能做错了什么。

预期输出:63494

【问题讨论】:

  • 也许网站上的顶级声明可能会解释一些事情:This is sandbox to test JavaScript regular expression. To test JAVA regular expression you can use java-applet
  • @N Deepak 你想要第二行吗?
  • @Eypros,我只使用 Java-Applet。请检查链接,我已分享。
  • 你要打印哪个id?

标签: java regex


【解决方案1】:

我认为您正在尝试打印 USER DEEPAK 的 ID。如果是,那么您的代码将是,

Pattern p = Pattern.compile("(?<= )[0-9]+(?=\\s*ABC\\s*DEEP\\s*[0-9]\\s*s)");
Matcher m = p.matcher(deepak);
while (m.find()) {
System.out.println(m.group());
}

IDEONE

【讨论】:

  • 我要打印63494
  • 打印输入加 63494。见 ideone 链接。
  • 您想打印63494 吗?然后从代码中删除System.out.println(deepak); 行。
【解决方案2】:

我会使用以下表达式:

"^\\s+(\\d+)\\s+(\\w+)\\s+(\\w+).+\$"

然后

group(1) is ID
group(2) is TYPE
group(3) is USER

表达式是非贪婪的,所以如果你不需要它们,你可以删除最后两组。

【讨论】:

    猜你喜欢
    • 2012-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多