Ryan Duffing
Ryan Duffing

Reputation: 674

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:

And not on the following:

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

Upvotes: 5

Views: 500

Answers (1)

anubhava
anubhava

Reputation: 785146

This negative lookahead should work:

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

RegEx Demo

Upvotes: 2

Related Questions