我正在编写这个正则表达式,因为我需要一种方法来查找没有n点的字符串,我虽然负向前看将是最好的选择,到目前为止我的正则表达式是:
"^(?!\\.{3})$"
Run Code Online (Sandbox Code Playgroud)
我读这个的方式是,在字符串的开始和结束之间,可以有多于或少于3个点而不是3.令人惊讶的是,这不匹配,hello.here.im.greetings
而是我期望匹配.我正在用Java写作,所以它的Perl就像味道一样,我没有逃避花括号,因为它不需要Java任何建议?
你走在正确的轨道上:
"^(?!(?:[^.]*\\.){3}[^.]*$)"
Run Code Online (Sandbox Code Playgroud)
将按预期工作.
你的正则表达式意味着
^ # 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
Run Code Online (Sandbox Code Playgroud)
所以它只能匹配空字符串.
我的正则表达式意味着:
^ # 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
Run Code Online (Sandbox Code Playgroud)
使用方法如下:
Pattern regex = Pattern.compile("^(?!(?:[^.]*\\.){3}[^.]*$)");
Matcher regexMatcher = regex.matcher(subjectString);
foundMatch = regexMatcher.find();
Run Code Online (Sandbox Code Playgroud)