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:

. I expect it to not match strings with double hyphens but it matches them.
For example,
matches this regex. I tried to escape hyphens like this
but still no success. What is the reason of this behaviour? Am I missing something?

Answer Source

Try this regex:


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.