saidfagan saidfagan - 25 days ago 7
Javascript Question

How to match string that does not have two hyphens with JavaScript regular expressions?

I have a JavaScript regex to match phone numbers:

/^(?!-{2}).*[0-9\-]{10,20}[0-9]$/
. I expect it to not match strings with double hyphens but it matches them.
For example,
9999-9999111999--9
matches this regex. I tried to escape hyphens like this
\-{2}
but still no success. What is the reason of this behaviour? Am I missing something?

Answer Source

Try this regex:

/^(?!.*--).*[0-9\-]{10,20}[0-9]/

The negative lookahead you want to use is ?!.*--, which says that two hyphens in sequence never appear anywhere in your input. Your current lookahead asserts that two hyphens do not appear in sequence at the very start of the string, but it places no such restrictions anywhere else.

As another comment, I question whether .* really makes sense at the start of your pattern. It seems way too open to me, almost wasting the effort elsewhere spent to craft a regex focusing on certain phone numbers.