1

I'm trying to write a password validator, and the validator requires an expression to match. If a password matches the when the expression is applied, the password is valid.

In this case, I'm trying to match on any valid password, except ones that contains three or more uninterrupted repeating characters. This could be any character, and it shouldn't matter where it occurs in the entire string.

Valid Passwords: Password1! Paasswwoorroodd1! <- I'd like these passwords to match. Note that there are 4 'o's in the second password, though only two 'o' appear one after the other, so it's valid.

Invalid Passwords: Password111! Passwooord!1 <- There are three repeating characters, back-to-back, therefore, I'd like it to not match.

In a previous attempt, I wrote a regular expression:

(.)\1{2}

Which allowed me to match repeating characters, but matching on everything BUT a string containing repeating characters is proving much more difficult.

Is it even possible to do through regex alone? I require a pure regex solution, rather than relying on running a match and manipulating it via code.

Any help would be appreciated.

Edit: Found my answer, thanks to Malte's comment below ^((.)\2?(?!\2))+$

Seems to match on all my criteria. I was missing the negative lookahead and the + at the end. Cheers.

Tom Case
  • 36
  • 4
  • Basically, use a negative lookahead anchored at the start, see [this answer](https://stackoverflow.com/a/2404330/3832970) in the linked thread. – Wiktor Stribiżew Jun 15 '17 at 08:13
  • Somehow my comment got lost. Look at this question which matches your specific question more closely: https://stackoverflow.com/questions/16717656/regex-no-more-than-2-identical-consecutive-characters-and-a-z-and-0-9 – Malte Hartwig Jun 15 '17 at 08:16
  • Malte, thanks for pointing me in the right direction. Using the regex `^((.)\2?(?!\2))+$` seems to do exactly what I needed. I was only a few characters off. – Tom Case Jun 15 '17 at 08:31

0 Answers0