Regular expression to match phone number

I need a regex to match phone numbers. I just want to know if the number is probably a phone number, and it can be any phone format, US or international. So I developed a strategy to determine if it fits.

I want it to accept the following characters:, 0-9as well as ,.()-optionally starting with +(for international numbers). A string must not match if it contains other characters.

I tried this:

/\+?[0-9\/\.\(\)\-]/

But it matches the phone numbers that have + in the middle of the number. And it matches the numbers that contain alpha characters (I don't want this).

Finally, I want to set the minimum length to 9 characters.

Any thoughts?

Thanks for any help, I'm obviously not too fast on RegEx materials :)

+3
source share
3 answers

Ok, you're pretty close. Try the following:

^\+?[0-9\/.()-]{9,}$

Without start and end anchors, you allow a partial match, so it can match +123from a string :-)+123.

If you need at least 9 digits and not any characters (therefore ---...///invalid), you can use:

^\+?[\/.()-]*([0-9][\/.()-]*){9,}$

or, using lookahead - before matching the string for [0-9/.()-]*the regex engine it looks for (\D*\d){9}that consists of 9 digits, each digit that can be preceded by other characters (which we will check later).

^\+?(?=(\D*\d){9})[0-9\/.()-]*$
+4
source

, -, . . , , VIM:

^+\?[()\-\.]\?\([0-9][\.()\-]\?\)\{3,\}$
+1

Juqeury has a plugin to test the phone in the USA. Check out the link. You can also see the regular expression in the source code.

0
source

Source: https://habr.com/ru/post/1779332/


All Articles