What regular expression using java could be used to filter out dashes '-' and open close round brackets from a string representing phone numbers...
使用java的正则表达式可以用来过滤掉dashes的“-”,并从代表电话号码的字符串中打开封闭的括号。
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,
谢谢,
2 个解决方案
#1
60
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.
正则表达式定义了一个由任何空格字符组成的字符类(\s,它被转义成\s,因为我们传入了一个字符串)、一个破折号(转义是因为破折号在字符类上下文中是特殊的)和圆括号。
See String.replaceAll(String, String)
.
看到字符串。replaceAll(字符串,字符串)。
EDIT
编辑
Per gunslinger47:
每gunslinger47:
phoneNumber.replaceAll("\\D", "");
Replaces any non-digit with an empty string.
用空字符串替换任何非数字。
#2
4
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;
}
#1
60
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.
正则表达式定义了一个由任何空格字符组成的字符类(\s,它被转义成\s,因为我们传入了一个字符串)、一个破折号(转义是因为破折号在字符类上下文中是特殊的)和圆括号。
See String.replaceAll(String, String)
.
看到字符串。replaceAll(字符串,字符串)。
EDIT
编辑
Per gunslinger47:
每gunslinger47:
phoneNumber.replaceAll("\\D", "");
Replaces any non-digit with an empty string.
用空字符串替换任何非数字。
#2
4
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;
}