What is the regex to match a string not containing

2020-05-02 20:52发布

I want to match strings that do not contain more than 3 of the same character repeated in a row. So:

  • abaaaa [no match]
  • abawdasd [match]
  • abbbbasda [no match]
  • bbabbabba [match]

Yes, it would be much easier and neater to do a regex match for containing the consecutive characters, and then negate that in the code afterwards. However, in this case that is not possible.

I would like to open out the question to x consecutive characters so that it can be extended to the general case to make the question and answer more useful.

Negative lookahead is supported in this case.

3条回答
相关推荐>>
2楼-- · 2020-05-02 21:13

I'm answering this question :

Is there a regular expression for matching a string that has no more than 2 repeating characters?

which was marked as an exact duplicate of this question.


Its much quicker to negate the match instead

if (!Regex.Match("hello world", @"(.)\1{2}").Success) Console.WriteLine("No dups");
查看更多
该账号已被封号
3楼-- · 2020-05-02 21:22

Use a negative lookahead with back references:

^(?:(.)(?!\1\1))*$

See live demo using your examples.

(.) captures each character in group 1 and the negative look ahead asserts that the next 2 chars are not repeats of the captured character.

查看更多
来,给爷笑一个
4楼-- · 2020-05-02 21:24

To match strings not containing a character repeated more than 3 times consecutively:

^((.)\2?(?!\2\2))+$

How it works:

^            Start of string
(
  (.)        Match any character (not a new line) and store it for back reference.
    \2?      Optionally match one more exact copies of that character.
    (?!      Make sure the upcoming character(s) is/are not the same character.
      \2\2   Repeat '\2' for as many times as you need
    )
)+           Do ad nauseam
$            End of string

So, the number of /2 in your whole expression will be the number of times you allow a character to be repeated consecutively, any more and you won't get a match.

E.g.

  • ^((.)\2?(?!\2\2\2))+$ will match all strings that don't repeat a character more than 4 times in a row.

  • ^((.)\2?(?!\2\2\2\2))+$ will match all strings that don't repeat a character more than 5 times in a row.

Please be aware this solution uses negative lookahead, but not all not all regex flavors support it.

查看更多
登录 后发表回答