验证国际电话号码的 Java 正则表达式

验证国际电话号码的 Java 正则表达式

原文: https://howtodoinjava.com/regex/java-regex-validate-international-phone-numbers/

在本正则表达式教程中,我们将学习根据 ITU-T E.123 指定的行业标准符号来验证国际电话号码

全球范围内用于打印国际电话号码的规则和约定千差万别,因此除非您采用严格的格式,否则很难为国际电话号码提供有意义的验证。 幸运的是,ITU-T E.123 指定了一种简单的行业标准符号。 此符号要求国际电话号码包含一个加号(称为国际前缀符号),并且只能使用空格分隔数字组。

同样,由于国际电话编号计划(ITU-T E.164),电话号码不能包含超过 15 位的数字。 使用的最短国际电话号码包含七个数字。

1. 验证国际电话号码的正则表达式

正则表达式:^\+(?:[0-9] ?){6,14}[0-9]$

^ # Assert position at the beginning of the string.
 \+ # Match a literal "+" character.
 (?: # Group but don't capture:
 [0-9] # Match a digit.
 \\s # Match a space character
 ? # between zero and one time.
 ) # End the noncapturing group.
 {6,14} # Repeat the group between 6 and 14 times.
 [0-9] # Match a digit.
 $ # Assert position at the end of the string.

以上正则表达式可用于验证基于 ITU-T 标准的国际电话号码。 让我们看一个例子。

List phoneNumbers = new ArrayList();
phoneNumbers.add("+1 1234567890123");
phoneNumbers.add("+12 123456789");
phoneNumbers.add("+123 123456");

String regex = "^\\+(?:[0-9] ?){6,14}[0-9]$";

Pattern pattern = Pattern.compile(regex);

for(String email : phoneNumbers)
{
	Matcher matcher = pattern.matcher(email);
	System.out.println(email +" : "+ matcher.matches());
}

Output:

+1 1234567890123 : true
+12 123456789 : true
+123 123456 : true

2. 验证 EPP 格式的国际电话号码

此正则表达式遵循可扩展配置协议(EPP)指定的国际电话号码符号。 EPP 是一个相对较新的协议(于 2004 年最终确定),旨在用于域名注册机构和注册商之间的通信。 越来越多的域名注册机构使用它,包括.com.info.net.org.us。 这样做的意义在于,越来越多的人使用和认可 EPP 样式的国际电话号码,因此提供了一种很好的替代格式来存储(和验证)国际电话号码。

EPP 样式的电话号码使用+CCC.NNNNNNNNNNxEEEE格式,其中C是 1-3 位国家/地区代码,N最多 14 位数字,E是(可选)扩展名。 国家/地区代码后必须加上加号和加点。 仅在提供扩展名时才需要字面“x”字符。

正则表达式:^\+[0-9]{1,3}\.[0-9]{4,14}(?:x.+)?$

List phoneNumbers = new ArrayList();
phoneNumbers.add("+123.123456x4444");
phoneNumbers.add("+12.1234x11");
phoneNumbers.add("+1.123456789012x123456789");

String regex = "^\\+[0-9]{1,3}\\.[0-9]{4,14}(?:x.+)?$";

Pattern pattern = Pattern.compile(regex);

for(String email : phoneNumbers)   
{
	Matcher matcher = pattern.matcher(email);
	System.out.println(email +" : "+ matcher.matches());
}

Output:

+123.123456x4444 : true
+12.1234x11 : true
+1.123456789012x123456789 : true

您可以随时在正则表达式上方进行编辑并使用它来匹配更严格的电话号码格式。

学习愉快!