Java 从电话号码中删除破折号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2717421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 12:03:34  来源:igfitidea点击:

Remove dash from a phone number

javaregexphone-number

提问by zoom_pat277

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

使用 java 的正则表达式可用于过滤掉破折号“-”并从代表电话号码的字符串中打开关闭圆括号......

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

所以 (234) 887-9999 应该给出 2348879999,同样地 234-887-9999 应该给出 2348879999。

Thanks,

谢谢,

采纳答案by Vivin Paliath

phoneNumber.replaceAll("[\s\-()]", "");

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

正则表达式定义了一个字符类,它由任何空白字符 ( \s\\s因为我们传入一个字符串而被转义)、一个破折号(因为破折号在字符类的上下文中意味着一些特殊的东西而被转义)和括号组成。

See String.replaceAll(String, String).

String.replaceAll(String, String)

EDIT

编辑

Per gunslinger47:

gunslinger47

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

Replaces any non-digit with an empty string.

用空字符串替换任何非数字。

回答by Tharaka Devinda

    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+"")         //if the number is starting with no zero and +, its a local number. prepend cc
                        .replaceAll("(.)(\++)(.)", "")         //if there are left out +'s in the middle by mistake, remove them
                        .replaceAll("(^0{2}|^\+)(.+)", "")       //make 00XXX... numbers and +XXXXX.. numbers into XXXX...
                        .replaceAll("^0([1-9])", countryCode+"");         //make 0XXXXXXX numbers into CCXXXXXXXX numbers
         return out;

    }