正则表达式模式,可匹配没有任何2个连续重复字符的字符串 [英] Regular expression pattern to match string without any 2 consecutive repeated characters
问题描述
我可以很容易地编写一个正则表达式来匹配包含2个连续重复字符的字符串:
I can very easily write a regular expression to match a string that contains 2 consecutive repeated characters:
/(\w)\1/
我该如何做呢?我想匹配没有2个连续重复字符的字符串.我尝试了以下各种变体,但均未成功:
How do I do the complement of that? I want to match strings that don't have 2 consecutive repeated characters. I've tried variations of the following without success:
/(\w)[^\1]/ ;doesn't work as hoped
/(?!(\w)\1)/ ;looks ahead, but some portion of the string will match
/(\w)(?!\1)/ ;again, some portion of the string will match
我不希望使用任何特定于语言/平台的方式来取反正则表达式.我想要一种简单的方法.
I don't want any language/platform specific way to take the negation of a regular expression. I want the straightforward way to do this.
推荐答案
下面的正则表达式将匹配没有重复字符的字符串.
The below regex would match the strings which don't have any repeated characters.
^(?!.*(\w)\1).*
(?!.*(\w)\1)
否定前瞻,它断言要匹配的字符串将不包含任何重复的字符. .*(\w)\1
将匹配在中间或开头或结尾重复字符的字符串. ^(?!.*(\w)\1)
匹配除具有重复字符的边界以外的所有起始边界.并且以下.*
匹配该特定行上存在的所有字符.请注意,这也匹配空字符串.如果您不想匹配空行,请最后将.*
更改为.+
(?!.*(\w)\1)
negative lookahead which asserts that the string going to be matched won't contain any repeated characters. .*(\w)\1
will match the string which has repeated characters at the middle or at the start or at the end. ^(?!.*(\w)\1)
matches all the starting boundaries except the one which has repeated characters. And the following .*
matches all the characters exists on that particular line. Note this this matches empty strings also. If you don't want to match empty lines then change .*
at the last to .+
请注意,^(?!(\w)\1)
仅在字符串或行的开头检查重复的字符.
Note that ^(?!(\w)\1)
checks for the repeated characters only at the start of a string or line.
前瞻性和后视性统称为环顾四周" ,它们都是零长度的断言就像行的开始和结束一样.它们不使用字符串中的字符,而仅声明是否可以匹配.环顾四周功能可让您创建没有正则表达式就无法创建的正则表达式,或者如果没有正则表达式会非常冗长.
Lookahead and lookbehind, collectively called "lookaround", are zero-length assertions just like the start and end of line. They do not consume characters in the string, but only assert whether a match is possible or not. Lookaround allows you to create regular expressions that are impossible to create without them, or that would get very longwinded without them.
这篇关于正则表达式模式,可匹配没有任何2个连续重复字符的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!