Writing Regex for phonenumber

Viewed 191

I want to write a regex to match phone numbers in following format i.e.

1- without country code 9999999999

2 - with 1 digit country code +19999999999

3 - with country code and () +1(999)9999999

4 - with country code () and - +1(999)-999-9999

I wrote a regex which matches condition 2 but failed in 1,3 and 4.

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

As soon as I adds country code after + sign along with () and - my regex stops working.

How Can I fix it? I am not a regex pro and assembled my regex by trying different patterns that I got by googling.

Any help would be appreciated.

2 Answers

EDIT: Since OP has added sample of phone numbers to be matched with + sign so adding following answer now.

^(?:\d{10})?(?:\+)?(?:(?:\d{11})?(?:\d\(\d{3}\))?(?:(?:\d{7})?(?:-\d{3}-\d{4})?))$

Here is Online demo for above regex



With your shown samples, could you please try following.

^\+(?:(?:\d{11})?(?:\d\(\d{3}\))?(?:(?:\d{7})?(?:-\d{3}-\d{4})?))$

Here is Online demo for above regex

Explanation: Adding detailed explanation for above.

^\+                        ##Checking if starting is from + sign.
(?:                        ##Starting a non-capturing group from here.
   (?:\d{11})?             ##Starting a non-capturing group which matches 11 digits here, keeping it optional.
   (?:\d\(\d{3}\))?        ##Starting a non-capturing group which matches single digit followed by ( 3 digits followed by ) and keeping this optional too.
   (?:                     ##Starting a non-capturing group here.
     (?:\d{7})?            ##Starting a non-capturing group here with 7 digits keeping it optional.
     (?:-\d{3}-\d{4})?     ##Starting a non-capturing group which has - 3 digits - 4 digits keep it optional.
   )                       ##Closing above non-capturing group here.
)$                         ##Closing very first non-capturing group here.

Here is my two cents to your question. It looks like the following ticks the boxes too:

^(?:\+\d(?:\(\d{3}\)(?:-\d{3}-|\d{3})|\d{6})|\d{6})\d{4}$

See an online demo

  • ^ - Start line anchor.
  • (?: - Open 1st non-capture group:
    • \+\d - A literal "+" and a single digit.
    • (?: - Open 2nd non-capture group:
      • \(\d{3}\) - Match three digits between opening and closing paranthesis.
      • (?: - Open 3rd non-capture group:
        • -\d{3}- - Three digits between dashes.
        • | - Or:
        • \d{3}) - Just three digits before closing 3rd non-capture group.
      • | - Or:
      • \d{6}) - Just six digits before closing 2nd non-capture group.
    • | - Or:
    • \d{6}) - Or just six digits before closing 1st non-capture group.
  • \d{4} - Four digits.
  • $ - End line anchor.

Add an optional digit to the pattern to allow for 2-digit countrycodes too, e.g:

^(?:\+\d\d?(?:\(\d{3}\)(?:-\d{3}-|\d{3})|\d{6})|\d{6})\d{4}$
Related