Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove parentheses, dashes, and spaces from phone number

Tags:

java

regex

I have a phone number like (123) 456-7890. I am using the replaceAll method to remove () and - and spaces from the string. I tried following

String phNo= "(123) 456-7890".replaceAll("[()-\\s]").trim();

but it's not working. Any solution?

like image 819
user3786942 Avatar asked Aug 01 '14 22:08

user3786942


2 Answers

This should work:

String phNo = "(123) 456-7890".replaceAll("[()\\s-]+", "");

In your regex:

  • \s should be \\s
  • Hyphen should be first or last in character class to avoid escaping or use it as \\-
  • Use quantifier + as in [()\\s-]+ to increase efficiency by minimizing # of replacements
like image 78
anubhava Avatar answered Sep 19 '22 20:09

anubhava


If you are using Kotlin than

mobileNo.replace(Regex("[()\\-\\s]"), "")

like image 22
Mohit Suthar Avatar answered Sep 16 '22 20:09

Mohit Suthar