原文: 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]$

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

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

  1. List phoneNumbers = new ArrayList();
  2. phoneNumbers.add("+1 1234567890123");
  3. phoneNumbers.add("+12 123456789");
  4. phoneNumbers.add("+123 123456");
  5. String regex = "^\\+(?:[0-9] ?){6,14}[0-9]$";
  6. Pattern pattern = Pattern.compile(regex);
  7. for(String email : phoneNumbers)
  8. {
  9. Matcher matcher = pattern.matcher(email);
  10. System.out.println(email +" : "+ matcher.matches());
  11. }
  12. Output:
  13. +1 1234567890123 : true
  14. +12 123456789 : true
  15. +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.+)?$

  1. List phoneNumbers = new ArrayList();
  2. phoneNumbers.add("+123.123456x4444");
  3. phoneNumbers.add("+12.1234x11");
  4. phoneNumbers.add("+1.123456789012x123456789");
  5. String regex = "^\\+[0-9]{1,3}\\.[0-9]{4,14}(?:x.+)?$";
  6. Pattern pattern = Pattern.compile(regex);
  7. for(String email : phoneNumbers)
  8. {
  9. Matcher matcher = pattern.matcher(email);
  10. System.out.println(email +" : "+ matcher.matches());
  11. }
  12. Output:
  13. +123.123456x4444 : true
  14. +12.1234x11 : true
  15. +1.123456789012x123456789 : true

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

学习愉快!