我正在编写这个正则表达式,因为我需要一种方法来查找没有n个点的字符串。我认为负向先行断言是最好的选择,目前我的正则表达式是:
"^(?!\\.{3})$"
我的理解是,在字符串的开头和结尾之间,可能有多于或少于3个点,但不能刚好为3个。
令我惊讶的是,这与 hello.here.im.greetings
不匹配,而我原本预期它应该匹配。
我在使用Java编写代码,所以它是Perl风格的,我不需要在Java中转义花括号。
有什么建议吗?
我正在编写这个正则表达式,因为我需要一种方法来查找没有n个点的字符串。我认为负向先行断言是最好的选择,目前我的正则表达式是:
"^(?!\\.{3})$"
我的理解是,在字符串的开头和结尾之间,可能有多于或少于3个点,但不能刚好为3个。
令我惊讶的是,这与 hello.here.im.greetings
不匹配,而我原本预期它应该匹配。
我在使用Java编写代码,所以它是Perl风格的,我不需要在Java中转义花括号。
有什么建议吗?
您正在正确的轨道上:
"^(?!(?:[^.]*\\.){3}[^.]*$)"
will work as expected.
Your regex means
^ # Match the start of the string
(?!\\.{3}) # Make sure that there aren't three dots at the current position
$ # Match the end of the string
因此它只能匹配空字符串。
我的正则表达式的意思是:
^ # Match the start of the string
(?! # Make sure it's impossible to match...
(?: # the following:
[^.]* # any number of characters except dots
\\. # followed by a dot
){3} # exactly three times.
[^.]* # Now match only non-dot characters
$ # until the end of the string.
) # End of lookahead
使用方式如下:
Pattern regex = Pattern.compile("^(?!(?:[^.]*\\.){3}[^.]*$)");
Matcher regexMatcher = regex.matcher(subjectString);
foundMatch = regexMatcher.find();
.matcher()
方法(我建议不要使用它,因为它强制你匹配整个字符串,即使你在第三个点之后停止匹配),你必须在正则表达式的最后添加.*
。 - Tim Pietzcker你的正则表达式只匹配“不是”三个连续的点。你的示例似乎显示您想要在句子中“不”匹配3个点。
试试这个:^(?!(?:.*\\.){3})
演示+解释:http://regex101.com/r/bS0qW1
请查看Tims的答案。
.*
也会匹配点。 此外,如果您使用.matches()
方法,则最终的 .*
是不必要的。 - Tim Pietzcker