【发布时间】:2011-02-12 15:07:35
【问题描述】:
使用 java 的正则表达式可用于过滤掉破折号 '-' 并从代表电话号码的字符串中打开右圆括号...
所以 (234) 887-9999 应该给 2348879999 同样,234-887-9999 应该给出 2348879999。
谢谢,
【问题讨论】:
标签: java regex phone-number
使用 java 的正则表达式可用于过滤掉破折号 '-' 并从代表电话号码的字符串中打开右圆括号...
所以 (234) 887-9999 应该给 2348879999 同样,234-887-9999 应该给出 2348879999。
谢谢,
【问题讨论】:
标签: java regex phone-number
phoneNumber.replaceAll("[\\s\\-()]", "");
正则表达式定义了一个字符类,由任何空白字符(\s,转义为\\s,因为我们传入一个字符串),一个破折号(转义,因为破折号在上下文中意味着特殊的东西字符类)和括号。
见String.replaceAll(String, String)。
编辑
phoneNumber.replaceAll("\\D", "");
用空字符串替换任何非数字。
【讨论】:
"\\D"。更直接的说出了初衷。 “删除任何不是数字的东西。”
+。 phoneNumber.replaceAll("\\D", "") 的建议不够保守。
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;
}
【讨论】:
我的 Kotlin 版本的工作解决方案 -(扩展功能)
fun getMeMyNumber(number: String, countryCode: String): String? {
return number.replace("[^0-9\\+]".toRegex(), "") //remove all the non numbers (brackets dashes spaces etc.) except the + signs
.replace("(^[1-9].+)".toRegex(), "$countryCode$1") //if the number is starting with no zero and +, its a local number. prepend cc
.replace("(.)(\\++)(.)".toRegex(), "$1$3") //if there are left out +'s in the middle by mistake, remove them
.replace("(^0{2}|^\\+)(.+)".toRegex(), "$2") //make 00XXX... numbers and +XXXXX.. numbers into XXXX...
.replace("^0([1-9])".toRegex(), "$countryCode$1") //make 0XXXXXXX numbers into CCXXXXXXXX numbers
}
【讨论】: