skip to Main Content

I’m trying to create a regex to find phone numbers in a text. Format of the phone number is unknown and it is a pretty complex topic in general, so I’m trying to keep it as simple as possible and just find POSSIBLE phone numbers (I can check them later with, for example, libphonenumber-js).

This is what I have at the moment:

/+?[d(][d()- ]{3,}d/g

This regexp finds phone numbers which satisfy:

  1. it can have "+" or not
  2. then there will be a number or opening parenthesis
  3. then just range of characters (numbers, parenthesis, dash or space, at least 3)
  4. will end up with a number

But my regex fails at these cases:

  • "+(651)-234-2345 (332)-445-12345", so here we see that the user failed to properly format phone number and forgot to add "+", and since parenthesis can repeat as many times as they want, I’m capturing it as one long number
  • "+(651)-234-2345(332)-445-12345" same as before, but now the user even forgot to add space

Is there a way to say, that parenthesis can only open and close once, or something like that?
I mean they can appear anywhere in the number, not only in the beginning, but just once.

I have a playground here: https://regexr.com/7lgni
As you can see, most of the phone numbers are highlighted as expected.

2

Answers


  1. Don’t mix () in with the digits. Just match one optional sequence beginning with (, ending with ), with digits in between. Then match combinations of digits, dashes, and spaces after that.

    +?(?:(d+))?[d-s]{3,}
    

    DEMO

    Login or Signup to reply.
  2. Given the relaxed requirements of a single, optional parenthesis pair and no
    following dash without accompanying digit.

    +?(?:d|(?:([d -]+)))[d -]{3,}d(?![d-])
    

    https://regex101.com/r/xSW0fs/1

    +? 
    (?:
       d 
     | (?: ( [d -]+ ) )
    )
    [d -]{3,} d 
    (?! [d-] )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search