javascript – Regex: I have a range of characters I’m looking for, but I want to limit possible amount of repetitions of some of them
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:
- it can have “+” or not
- then there will be a number or opening parenthesis
- then just range of characters (numbers, parenthesis, dash or space, at least 3)
- 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: regexr.com/7lgni
As you can see, most of the phone numbers are highlighted as expected.
Read more here: Source link
