java - 有没有办法将电话号码标准化为 1-222-444-5555(根据北美标准)?
问题描述
我想知道是否有一种方法可以使用正则表达式模式将电话号码标准化为北美标准(1-222-333-4444)。
该字符串将仅采用“-”、空格、“(”、“)”和数字。
谢谢 :)
更新:所有可能的输入是:
(123)-456-7890
123-456-7890
1-(123)-456-7890
1-123-456-7890
(123) 456-7890
123 456-7890
1-(123) 456-7890
1-123 456-7890
(123) 456 7890
123 456 7890
1 123 456 7890
1 (123) 456 7890
代码尝试:
public String convertPhone(String newPhone) {
String regex = "^([\\(]{1}[0-9]{3}[\\)]{1}[ |\\-]{0,1}|^[0-9]{3}[\\-| ])?[0-9]{3}(\\-| ){1}[0-9]{4}$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(newPhone);
if (matcher.matches()) {
newPhone = matcher.replaceFirst("1 \\($1\\) $2-$3");
return newPhone;
} else {
return "-1";
}
}
解决方案
也许,类似于,
(?:1[ -])?[(]?(\d{3})[)]?[ -](\d{3})[ -](\d{4})$
可能涵盖问题中提供的示例,但可能会有边缘情况,例如任何意外的双空格。
正则表达式演示
测试
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegularExpression{
public static void main(String[] args){
final String regex = "(?m)(?:1[ -])?[(]?(\d{3})[)]?[ -](\d{3})[ -](\d{4})$";
final String string = "(123)-456-7890\n"
+ "123-456-7890\n"
+ "1-(123)-456-7890\n"
+ "1-123-456-7890\n"
+ "(123) 456-7890\n"
+ "123 456-7890\n"
+ "1-(123) 456-7890\n"
+ "1-123 456-7890\n"
+ "(123) 456 7890\n"
+ "123 456 7890\n"
+ "1 123 456 7890\n"
+ "1 (123) 456 7890";
final String subst = "1-$1-$2-$3";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
final String result = matcher.replaceAll(subst);
System.out.println(result);
}
}
输出
1-123-456-7890
1-123-456-7890
1-123-456-7890
1-123-456-7890
1-123-456-7890
1-123-456-7890
1-123-456-7890
1-123-456-7890
1-123-456-7890
1-123-456-7890
1-123-456-7890
1-123-456-7890
如果您希望简化/更新/探索表达式,它已在regex101.com的右上角面板中进行了说明。如果您有兴趣,可以在此调试器链接中观看匹配步骤或修改它们。调试器演示了 RegEx 引擎如何逐步使用一些示例输入字符串并执行匹配过程。
正则表达式电路
jex.im可视化正则表达式:
推荐阅读
- python - Docker_Error_Python_Couchdb sh:1:docker:未找到
- gitlab-api - 使用 API 列出 gitlab 项目
- python - 我如何使用二进制列表在 PyGame 中绘制正方形?
- android - Android/Kotlin - 如何循环所有 ToggleButtons 以创建 if/else 条件
- javascript - 如何在请求结果中使用变量来遍历数据?
- html - 使用引导程序 btn-group-toggle 在烧瓶中检索复选框按钮值的问题
- python - 有没有办法将多个字符串添加到 Text 对象?(泽尔图形)
- terraform - Terraform 资源使用模块生成多个 key_pair
- docker - DreamFactory 如何在 docker 容器中禁用包装器“资源”
- spring - spring boot打包后找不到资源文件