views:

328

answers:

1

What regular expression using java could be used to filter out dashes '-' and open close round brackets from a string representing phone numbers...

so that (234) 887-9999 should give 2348879999 and similarly 234-887-9999 should give 2348879999.

Thanks,

+7  A: 
phoneNumber.replaceAll("[\\s\\-()]", "");

The regular expression defines a character class consisting of any whitespace character (\s, which is escaped as \\s because we're passing in a String), a dash (escaped because a dash means something special in the context of character classes), and parentheses.

See String.replaceAll(String, String).

EDIT

Per gunslinger47:

phoneNumber.replaceAll("\\D", "");

Replaces any non-digit with an empty string.

Vivin Paliath
Might be best to just go for `"\\D"`. It speaks the original intention more directly. "Remove anything that's not a digit."
Gunslinger47
Both of the above works in my case... because I limit the user to enter only digits,, round brackets and dashes... Thanks a lot guys :)
zoom_pat277
@Gunslinger - that's a good point. I'll edit my solution.
Vivin Paliath