Remove dash from a phone number

♀尐吖头ヾ 提交于 2019-11-28 22:21:11

问题


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,


回答1:


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.




回答2:


    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;

    }


来源:https://stackoverflow.com/questions/2717421/remove-dash-from-a-phone-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!