我想知道是否有办法使用正则表达式将电话号码标准化为北美标准(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";
}
}
为什么不只删除非数字字符,然后根据字符串长度重新格式化原始数字。
String[] phoneNumbers = {
"(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"
};
for (String phone : phoneNumbers) {
String ph = phone.replaceAll("[\\(\\)\\- ]", "");
if (ph.length() == 11) {
ph = ph.substring(1);
}
String ac = ph.substring(0, 3);
String exc = ph.substring(3, 6);
String number = ph.substring(6);
number = String.format("1 (%s) %s-%s", ac, exc, number);
System.out.println(number);
}
也许是类似的表达,
(?: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的右上角进行说明。如果您有兴趣,可以观看匹配的步骤或在this debugger link中进行修改。调试器演示了a RegEx engine如何逐步使用一些示例输入字符串并执行匹配过程。
[jex.im可视化正则表达式:
我认为可以通过简单地查找数字,而忽略国家代码和数字组之间的所有内容来完成。此正则表达式可以处理所有多余的空格或任何非数字字符且数字之间没有空格的所有示例和情况。
1?\D*(\d{3})\D*(\d{3})\D*(\d{4})\b
然后您可以使用此模式替换数字。
1-$1-$2-$3