Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove dash from a phone number

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,

like image 751
zoom_pat277 Avatar asked Apr 26 '10 22:04

zoom_pat277


People also ask

How do I remove dashes from a phone number in Java?

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

How do I remove dashes from SSN in Excel and keep leading zeros?

Click the corner of the cell, with the "+" sign still showing, and drag the cursor down through the column until you reach the cell to the right of the last Social Security number in the list. Release the cursor, and the remaining SSNs will appear without hyphens.

How do I remove dashes from an Excel column?

Type the formula =SUBSTITUTE(Cell1,"-","") into the "fx" text box. You can replace the "Cell1" section with the name of the cell you want to delete dashes from and press the enter button on your keyboard. Continue using the SUBSTITUTE formula to delete dashes from individual cells throughout your Excel spreadsheet.


2 Answers

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.

like image 164
Vivin Paliath Avatar answered Sep 27 '22 21:09

Vivin Paliath


    public static String getMeMyNumber(String number, String countryCode)
    {    
         String out = number.replaceAll("[^0-9\\+]", "")        //remove all the non numbers (brackets dashes spaces etc.) except the + signs
                        .replaceAll("(^[1-9].+)", countryCode+"$1")         //if the number is starting with no zero and +, its a local number. prepend cc
                        .replaceAll("(.)(\\++)(.)", "$1$3")         //if there are left out +'s in the middle by mistake, remove them
                        .replaceAll("(^0{2}|^\\+)(.+)", "$2")       //make 00XXX... numbers and +XXXXX.. numbers into XXXX...
                        .replaceAll("^0([1-9])", countryCode+"$1");         //make 0XXXXXXX numbers into CCXXXXXXXX numbers
         return out;

    }
like image 39
Tharaka Devinda Avatar answered Sep 27 '22 20:09

Tharaka Devinda