SJackson193 SJackson193 - 29 days ago 6
Java Question

Valid regex expression?

I have this string:


+1(333) 456-7890


I want to match it with a regular expression. This is what I have now for my regex pattern:

Pattern p1 = Pattern.compile("((\\+{0,}[0-9]{0,3}( |-)?)?)(\\(?[0-9]
{3}\\)?|[0-9]{3}( |-)?)([0-9]{3}( |-)?)([0-9]{4}|[a-zA-Z0-9]{7})");


It is supposed to recognize any phone number pattern with potential dashes or spaces in the middle, that could be at least 10 digits (or letters), with no country code and at most 13 digits with a country code.

My pattern seems to match certain cases and not others such as the one previously stated. I'm really stumped, any help would be appreciated.

dda dda
Answer

Your regex seems overly complex, which is why it probably breaks somewhere. I tried to follow it but in the end it was easier to read your definition and build a new one from scratch:

(\+\d{1,3}[- ]*)?(\(?\d\d\d\)?)[- ]*(\d\d\d[- ]?\d\d\d\d|[a-zA-Z0-9]{7})

This matches the following test cases:

+1(333) 456-7890

+1-(212) 555-0198

+1 212 555-0198

+1 212-ILOVEUU

Depending on your own test cases, this might be enough. Or not.

(\+\d{1,3}[- ]*)?     // Optional +xxx international prefix plus dash/space
(\(?\d\d\d\)?)[- ]*   // three-digit area code with optional parens
(\d\d\d[- ]?\d\d\d\d| // Either 7 digits, with optional dash
[a-zA-Z0-9]{7})       // or 7 letters/digits