Java 正则表达式不工作 - 为什么?

发布于 2024-08-03 22:19:32 字数 418 浏览 3 评论 0原文

match.matches() 返回 false。这很奇怪,因为如果我使用这个正则表达式并测试字符串到 rubular.com,则会显示两个匹配项。我做错了什么?

    Pattern regex = Pattern.compile("FTW(((?!ODP).)+)ODP");
    Matcher match = regex.matcher("ZZZMMMJJJOOFTWZMJZMJODPZZZMMMJJJOOOFTWMZJOMZJOMZJOODPZZZMMMJJJOO");

    if (match.matches()) {
        System.out.println("match found");
    }
    else {
        System.out.println("match not found");
    }

match.matches() returns false. This is odd, because if I take this regex and test String to rubular.com, is shows two matches. What am I doing wrong?

    Pattern regex = Pattern.compile("FTW(((?!ODP).)+)ODP");
    Matcher match = regex.matcher("ZZZMMMJJJOOFTWZMJZMJODPZZZMMMJJJOOOFTWMZJOMZJOMZJOODPZZZMMMJJJOO");

    if (match.matches()) {
        System.out.println("match found");
    }
    else {
        System.out.println("match not found");
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

街角卖回忆 2024-08-10 22:19:32

Matcher.matches< /code>返回整个区域是否与模式匹配。

尝试使用 find< /code>相反。 (当然,对于您的示例,这效果很好。)

Matcher.matches returns whether or not the whole region matches the pattern.

Try using find instead. (Certainly with your example, this works fine.)

子栖 2024-08-10 22:19:32

Matcher.matches() 方法尝试将整个字符串与模式进行匹配。将您的模式更改为:

".*FTW(((?!ODP).)+)ODP.*"

The Matcher.matches() method tries to match the entire string to the pattern. Change your pattern to:

".*FTW(((?!ODP).)+)ODP.*"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文