即使模式正确,正则表达式匹配也不起作用

发布于 2024-10-08 14:12:20 字数 388 浏览 0 评论 0原文

我使用正则表达式已经有几年了,但如果我没记错的话,以下应该有效:

String test = "axaxa";
Pattern p = Pattern.compile("([a-c])x\1x\1");
Matcher m = p.matcher(test);

m 在运行时不匹配任何内容。这是我在代码中所做的超级简化版本。该示例实际上取自关于正则表达式的 Java 教程!我试图重写我的 html 匹配代码,当时它不起作用,我去研究,认为我做错了什么......根据互联网,我没有。所以。有谁知道为什么这不起作用?

额外信息,test.matches(the_pattern) 返回 false。看来团体回溯把事情搞砸了。

It's been a few years since I've used regex, but if I remember correctly, the following should work:

String test = "axaxa";
Pattern p = Pattern.compile("([a-c])x\1x\1");
Matcher m = p.matcher(test);

m matches nothing on run. This is a super simplified version of what I'm doing in my code. That example is actually taken from a Java tutorial on regex! I tried to rewrite my html matching code from way back when it didn't work, I went to researching, thinking I did something wrong... which according to the Internet, I haven't. So. Does anyone have a clue as to why this doesn't work?

Extra info, test.matches(the_pattern) returns false. It seems like the group backtracking is messing it up.

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

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

发布评论

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

评论(2

二智少女 2024-10-15 14:12:20

尝试以 \1 的速度使用 \\1

\ 是Java字符串中的转义字符。要将 \1 发送到正则表达式引擎,我们需要将 \ 转义为 \\1

Try using \\1 in pace of \1.

\ is the escape character in Java string. To send a \1 to regex engine, we need to escape the \ as \\1.

奢望 2024-10-15 14:12:20

在 Java 中,我们必须转义反斜杠:

Pattern p = Pattern.compile("([a-c])x\\1x\\1");

In Java we have to escape the backslashes:

Pattern p = Pattern.compile("([a-c])x\\1x\\1");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文