使用java的正则表达式可用于过滤掉破折号'-'并从代表电话号码的字符串中打开右圆括号......
所以 (234) 887-9999 应该给出 2348879999 并且类似地 234-887-9999 应该给出 2348879999。
谢谢,
使用java的正则表达式可用于过滤掉破折号'-'并从代表电话号码的字符串中打开右圆括号......
所以 (234) 887-9999 应该给出 2348879999 并且类似地 234-887-9999 应该给出 2348879999。
谢谢,
phoneNumber.replaceAll("[\\s\\-()]", "");
正则表达式定义了一个字符类,它由任何空白字符 ( \s
,\\s
因为我们传入一个字符串而被转义)、一个破折号(因为破折号在字符类的上下文中意味着特殊的东西而被转义)和括号组成。
见String.replaceAll(String, String)
。
编辑
每个gunslinger47:
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
}