使用 java 的正则表达式可用于过滤掉破折号“-”并从表示电话号码的字符串中打开右圆括号…
这样 (234) 887-9999 应该给出 2348879999,同样 234-887-9999 应该给出 2348879999。
谢谢,
原文由 zoom_pat277 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用 java 的正则表达式可用于过滤掉破折号“-”并从表示电话号码的字符串中打开右圆括号…
这样 (234) 887-9999 应该给出 2348879999,同样 234-887-9999 应该给出 2348879999。
谢谢,
原文由 zoom_pat277 发布,翻译遵循 CC BY-SA 4.0 许可协议
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;
}
原文由 Tharaka Devinda 发布,翻译遵循 CC BY-SA 3.0 许可协议
15 回答8.4k 阅读
8 回答6.3k 阅读
1 回答4.1k 阅读✓ 已解决
3 回答2.2k 阅读✓ 已解决
2 回答3.1k 阅读
2 回答3.8k 阅读
1 回答2.1k 阅读✓ 已解决
正则表达式定义了一个由任何空白字符组成的字符类(
\s
,它被转义为\\s
因为我们传入的是一个字符串),一个破折号(转义是因为破折号意味着在字符类的上下文中有一些特殊的东西)和括号。请参阅
String.replaceAll(String, String)
。编辑
每个 gunslinger47 :
用空字符串替换任何非数字。