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?
Asked
Active
Viewed 687 times
-1

saidfagan
- 841
- 2
- 9
- 26
-
Remove hyphen from squares – SubjectDelta Sep 22 '17 at 13:08
-
1You need to put `.*` into the lookahead. `/^(?!.*-{2})[0-9\-]{10,20}[0-9]$/` – Wiktor Stribiżew Sep 22 '17 at 13:09
-
That worked, thanks Wiktor. – saidfagan Sep 22 '17 at 13:14
1 Answers
0
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.

Tim Biegeleisen
- 502,043
- 27
- 286
- 360
-
Thanks for good explanation. Yes, `.*` in the beginning of the pattern is wrong. – saidfagan Sep 22 '17 at 13:17