Regex not matching 6 repeated numbers

2k views Asked by At

I am trying to get a regular expression to work but am stumped. What I want is to do the inverse of this:

/(\w)\1{5,}/

This regex does the exact opposite of what I'm trying to do. I would like to get everything but a string that has 6 repeating numbers i.e. 111111 or 999999.

Is there a way to use a negative look-around or something with this regex?

2

There are 2 answers

0
anubhava On BEST ANSWER

You can use this rgex:

/^(?!.*?(\w)\1{5}).*$/gm

RegEx Demo

(?!.*?(\w)\1{5}) is a negative lookaahead that will fail the match if there are 6 consecutive same word characters in it.

2
Wiktor Stribiżew On

I'd rather go with the \d shorthand class for digits since \w also allows letters and an underscore.

^(?!.*(\d)\1{5}).*$

Regex explanation:

  • ^ - Start of string/line anchor
  • (?!.*(\d)\1{5}) - The negative lookahead checking if after an optional number of characters (.*) we have a digit ((\d)) that is immediately followed with 5 identical digits (\1{5}).
  • .* - Match 0 or more characters up to the
  • $ - End of string/line.

See demo. This regex will allow