首页 > 解决方案 > 有没有办法将电话号码标准化为 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";
    }
}

标签: javaregexstring-parsing

解决方案


也许,类似于,

(?: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可视化正则表达式:

在此处输入图像描述


推荐阅读