Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't negate regular expression

I'm trying to implement the negation of the following regular expression in JavaScript:

^(\d)\1+-(\d)\1+-(\d)\1+$

That expression matches on the following:

  • 11111-111-11111
  • 22-2222-2222
  • 55-55555-55

And not on the following:

  • 12-22-3345
  • 32-44555-3333

I want it to do the opposite of those scenarios.

I've tried the following regular expressions and they do not work:

^(?!(\d)\1+-(\d)\1+-(\d)\1+)$
^(?!(\d))\1+-(?!(\d))\1+-(?!(\d))\1+$
^(?!(\d)\1+)-(?!(\d)\1+)-(?!(\d)\1+)$

I thought I had a solid understanding of what negative lookahead does, but apparently not. What am I doing wrong here? Can anyone point me in the right direction to a solution?

EDIT: Here's a link to mess around with the current regular expression: https://regex101.com/r/jY9mJ6/1

like image 539
Ryan Duffing Avatar asked Oct 20 '22 15:10

Ryan Duffing


1 Answers

This negative lookahead should work:

^(?!(\d)\1+-(\d)\1+-(\d)\1+$).*

RegEx Demo

like image 100
anubhava Avatar answered Oct 22 '22 08:10

anubhava