[英]Simple regex to match strings containing <n> chars
I'm writing this regexp as i need a method to find strings that does not have n dots, I though that negative look ahead would be the best choice, so far my regexp is: 我正在编写这个正则表达式,因为我需要一种方法来查找没有n点的字符串,我虽然负向前看将是最好的选择,到目前为止我的正则表达式是:
"^(?!\\.{3})$"
The way i read this is, between start and end of the string, there can be more or less then 3 dots but not 3. Surprisingly for me this is not matching hello.here.im.greetings
Which instead i would expect to match. 我读这个的方式是,在字符串的开始和结束之间,可以有多于或少于3个点而不是3.令人惊讶的是,这不匹配
hello.here.im.greetings
而是我期望匹配。 I'm writing in Java so its a Perl like flavor, i'm not escaping the curly braces as its not needed in Java Any advice? 我正在用Java写作,所以它的Perl就像味道一样,我没有逃避花括号,因为它不需要Java任何建议?
You're on the right track: 你走在正确的轨道上:
"^(?!(?:[^.]*\\.){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
so it could only ever match the empty string. 所以它只能匹配空字符串。
My regex means: 我的正则表达式意味着:
^ # 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
Use it as follows: 使用方法如下:
Pattern regex = Pattern.compile("^(?!(?:[^.]*\\.){3}[^.]*$)");
Matcher regexMatcher = regex.matcher(subjectString);
foundMatch = regexMatcher.find();
Your regular expression only matches 'not' three consecutive dots.
您的正则表达式仅匹配“不”三个连续点。
Your example seems to show you want to 'not' match 3 dots anywhere in the sentence.
你的例子似乎表明你想要“不”匹配句子中任何地方的3个点。
Try this:
^(?!(?:.*\\\\.){3})
试试这个:
^(?!(?:.*\\\\.){3})
Demo+explanation:
http://regex101.com/r/bS0qW1
演示+解释:
http :
//regex101.com/r/bS0qW1
Check out Tims answer instead. 查看Tims的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.