即使模式正确,正则表达式匹配也不起作用
我使用正则表达式已经有几年了,但如果我没记错的话,以下应该有效:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试以
\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
.在 Java 中,我们必须转义反斜杠:
In Java we have to escape the backslashes: