0

I have created a reg Exp, which basically allows all formats I like it to allow. However, there still is a little problem with the ()...

^\(?(\+?\d+)?\)? ?\d*(-?\d{2,3} ?){0,4}$

This would be valid: (+356-123 456 78, however it shouldn't.... same for +356)-123 456 78.

Anyone knows how to make sure the pattern contains both () or none?

Kara
  • 6,115
  • 16
  • 50
  • 57
Jeffrey
  • 1,766
  • 2
  • 24
  • 44
  • http://stackoverflow.com/questions/9370903/java-regex-replacing-a-phone-number-including-optional-parentheses – Marc May 04 '12 at 00:40

3 Answers3

3

First, note you can't write a regular expression that checks for balanced parentheses. If you want to allow only one pair of parentheses, you can make a regex to ensure that they're either both present, or neither is. But if you want to allow any number of parentheses, but only in pairs, a regular expression is not powerful enough to do the job; you need an actual parser.

Personally, I would just strip the phone number of anything but digits, spaces, and the + sign. That's the international notation recommended by ITU-T standard E.123, and it removes the need to worry about parentheses.

Mark Reed
  • 91,912
  • 16
  • 138
  • 175
  • You can do it with backreferences and such, but is it worth all the trouble? – siride May 04 '12 at 00:47
  • *"you can't write a regular expression that checks for balanced parentheses"* - eg. `\((?R)*\)` – Qtax May 04 '12 at 02:17
  • What's (?R)? Anonymous recursion? In any case, once you have something like that, it's no longer really a 'regular expression'. – Mark Reed May 04 '12 at 02:24
2

Try this:

^(?:\((\+?\d+)?\)|\+?\d+) ?\d*(-?\d{2,3} ?){0,4}$

It allows the the area code to either have an area code with parenthesis or without.

Nick Clark
  • 4,439
  • 4
  • 23
  • 25
0

The easiest way to handle this is to strip non-numbers and normalize whitespace in phone number fields. People ten to type in many and foolish formats for phone number fields. I'd suggest a 2 step process:

// Strip non-numbers and whitespace
var cleanPhone = phoneNumber.replace( /[^0-9\s]/, "" );

// All whitespace are now single spaces
cleanPhone = cleanPhone.replace( /\s+/, " " );

if( cleanPhone.match(/* place your (now simple) validation regex here */) ) {
    // Valid!
}
Ben Roux
  • 7,308
  • 1
  • 18
  • 21