The regex for a phone number is 10 digits and allows "-" (Javascript)

so I got the score and one of the regex is a phone number which has 10 numbers but also allows a dash "-". However, it can only contain two dashes and start with a 0. for example. 0x-xxxx-xxxx, where x can be any digit between 0-9.

So, so far I have come across the following regular expressions:

^[0-0][0-9-]{1,11}$
^[0-0][0-9-]{11}$

      

In the first it works but allows any length if I put 5 numbers it goes through until the first is 0. In the second I can put 2 hyphens following one after the other, or just fill it with a dash and it goes through.

Thanks for helping the guys!

+3


source to share


1 answer


Match each of the three parts separated by strokes, for example:

^0\d-\d{4}-\d{4}$

      

This corresponds to 0x-xxxx-xxxx. Demo: https://regex101.com/r/nW7wL5/1

If you also want to match a number without a dash, use



^0\d-?\d{4}-?\d{4}$

      

Demo: https://regex101.com/r/gY0mC3/1

\d

is the same as [0-9]

but shorter.

+1


source







All Articles