[英]Regex not working in Java code although it works on regex websites
I guess I am just too tired, but I cannot figure it out after reading all the docs and tutorials. 我想我太累了,但是在阅读所有文档和教程后我无法弄清楚。 I have the following code: 我有以下代码:
import java.util.regex.*;
class Main {
public static void main(String args[]) {
String str = "ababaaabaaaaaabbbbbbaaaaaabaabababababaaaaaabbbbbbaaaaaabababababaaaaaabbbbbbaaaaaa";
Pattern regex = Pattern.compile("(([ab])\2{5})(?!\1)(([ab])\4{5})(?!\3)(([ab])\6{5})");
Matcher matcher = regex.matcher(str);
int counter666 = 0;
while (matcher.find()) ++counter666;
System.out.println(counter666);
}
}
I want to search the string for six occurrences of the same letter (should be a or b) three times after each other (but not three times the same letter). 我想在字符串中搜索三个重复出现的相同字母(应该是a或b)的六次出现(但不是相同字母的三倍)。 So, these are the only possible matches: 因此,这些是唯一可能的匹配项:
This regex is working on regex101 and on this page. 此正则表达式正在regex101和此页面上运行。 However, my code always returns zero instead of three. 但是,我的代码总是返回零而不是三个。 Is there any option I have to set to make it working? 我必须设置任何选项才能使其正常工作吗?
You're very very close. 你非常亲密。 In order for the regular expression to work in a Java String
you have to escape the \\
literals; 为了使正则表达式在Java String
您必须转义\\
文字; otherwise the compiler doesn't put the value in the String
(that you expect anyway). 否则,编译器不会将值放在String
(无论如何您都希望如此)。 Like, 喜欢,
Pattern regex = Pattern.compile(
"(([ab])\\2{5})(?!\\1)(([ab])\\4{5})(?!\\3)(([ab])\\6{5})");
And I get (with no other changes) 我得到(没有其他更改)
3
短版,步骤少,分为两组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.