我正在尝试从电话号码中删除+1 (国家代码)(我正在进行一个标准化项目)。例如,用户有一个+1(703)-555-5787格式的电话号码,他希望它是(703)-555-5787 (前面没有+1 )。
我的理论是可以根据正则表达式模式搜索phoneNum字符串。一旦找到它,我就可以打印它或做任何我喜欢的事情。我的代码如下所示:
public static String normalizePrefix(final String phoneNum) {
String ret = phoneNum;
if (!phoneNum.contains("+1")) {
logger.log(Level.INFO, "input phone number doesn't contain country code (+1)");
}
else {
String regex = "(\\+1)([2-9][0-9][0-9])-([2-9][0-9]{2})-([0-9]{4})";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(phoneNum);
if (phoneNum.matches(regex)){
ret = m.group().substring(2, m.end());
}
}
logger.log(Level.INFO, phoneNum + "-->" + ret);
return ret;
}我遗漏了什么?
发布于 2013-07-04 01:37:37
matches将尝试完全匹配模式..
因此,如果字符串之间有电话号码,那么正则表达式将不起作用。
使用Matcher的find方法
if (m.find())
{
ret = m.group().substring(2, m.group().length());
}发布于 2013-07-04 18:24:35
尝试regex:
String regex = "\\([0-9]{3}\\)-[0-9]{3}-[0-9]{4}";并将if块修改为:
if (m.find()){
ret = m.group(0);
}发布于 2013-07-04 19:42:45
我在这里尝试并测试了以下正则表达式:
String regex = "\\([0-9]{3}\\)-[0-9]{3}-[0-9]{4}";之后,修改if块:
if (m.matches()){
ret = m.group(2);
}这应该始终返回电话号码,无论是否有+1前缀。
https://stackoverflow.com/questions/17454632
复制相似问题