Validate Phone Numbers With Java Regex – 用Java Regex验证电话号码

最后修改: 2020年 5月 10日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

Sometimes, we need to validate text to ensure that its content complies with some format. In this quick tutorial, we’ll see how to validate different formats of phone numbers using regular expressions.

有时,我们需要对文本进行验证,以确保其内容符合某种格式。在这个快速教程中,我们将看到如何使用regular expressions验证不同格式的电话号码。

2. Regular Expressions to Validate Phone Numbers

2.用正则表达式验证电话号码

2.1. Ten-Digit Number

2.1.十位数的数字

Let’s start with a simple expression that will check if the number has ten digits and nothing else:

让我们从一个简单的表达式开始,这个表达式将检查数字是否有十位数,而不是其他

@Test
public void whenMatchesTenDigitsNumber_thenCorrect() {
    Pattern pattern = Pattern.compile("^\\d{10}$");
    Matcher matcher = pattern.matcher("2055550125");
    assertTrue(matcher.matches());
}

This expression will allow numbers like 2055550125.

这个表达式将允许像2055550125这样的数字。

2.2. Number With Whitespaces, Dots or Hyphens

2.2.带有空格、圆点或连字符的数字

In the second example, let’s see how we can allow optional whitespace, dots, or hyphens (-) between the numbers:

在第二个例子中,让我们看看如何在数字之间允许可选的空白、点或连字符(-)

@Test
public void whenMatchesTenDigitsNumberWhitespacesDotHyphen_thenCorrect() {
    Pattern pattern = Pattern.compile("^(\\d{3}[- .]?){2}\\d{4}$");
    Matcher matcher = pattern.matcher("202 555 0125");
    assertTrue(matcher.matches());
}

To achieve this extra goal (optional whitespace or hyphen), we’ve simply added the characters:

为了实现这个额外的目标(可选的空白或连字符),我们简单地添加了这些字符。

  • [- .]?

This pattern will allow numbers like 2055550125, 202 555 0125, 202.555.0125, and 202-555-0125.

这种模式将允许像2055550125202 555 0125202.555.0125202-555-0125的数字。

2.3. Number With Parentheses

2.3.带括号的数字

Next, let’s add the possibility to have the first part of our phone between parentheses:

接下来,让我们增加一个可能性,让我们的电话的第一部分在括号之间

@Test
public void whenMatchesTenDigitsNumberParenthesis_thenCorrect() {
    Pattern pattern = Pattern.compile"^((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$");
    Matcher matcher = pattern.matcher("(202) 555-0125");
    assertTrue(matcher.matches());
}

To allow the optional parenthesis in the number, we’ve added the following characters to our regular expression:

为了允许数字中出现可选的括号,我们在正则表达式中加入了以下字符。

  • (\\(\\d{3}\\))|\\d{3})

This expression will allow numbers like (202)5550125, (202) 555-0125 or (202)-555-0125. Additionally, this expression will also allow the phone numbers covered in the previous example.

这个表达式将允许像(202)5550125(202) 555-0125(202)-555-0125这样的数字。此外,这个表达式还将允许前面的例子中所涉及的电话号码。

2.4. Number With International Prefix

2.4.带有国际前缀的号码

Finally, let’s see how to allow an international prefix at the start of a phone number:

最后,让我们看看如何在电话号码的开头允许有国际前缀

@Test
public void whenMatchesTenDigitsNumberPrefix_thenCorrect() {
  Pattern pattern = Pattern.compile("^(\\+\\d{1,3}( )?)?((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$");
  Matcher matcher = pattern.matcher("+111 (202) 555-0125");
  
  assertTrue(matcher.matches());
}

To permit the prefix in our number, we have added to the beginning of our pattern the characters:

为了允许我们的数字中出现前缀,我们在图案的开头加上了这些字符。

  • (\\+\\d{1,3}( )?)?

This expression will enable phone numbers to include international prefixes, taking into account that international prefixes are normally numbers with a maximum of three digits.

这种表达方式将使电话号码包括国际前缀,考虑到国际前缀通常是最多三个数字的号码。

3. Applying Multiple Regular Expressions

3.应用多个正则表达式

As we’ve seen, a valid phone number can take on several different formats. Therefore, we may want to check if our String complies with any one of these formats.

正如我们所见,一个有效的电话号码可以有几种不同的格式。因此,我们可能想检查我们的String是否符合这些格式中的任何一种。

In the last section, we started with a simple expression and added more complexity to achieve the goal of covering more than one format. However, sometimes it’s not possible to use just one expression. In this section, we’ll see how to join multiple regular expressions into a single one.

在上一节中,我们从一个简单的表达式开始,增加了更多的复杂性,以达到覆盖一种以上的格式的目的。然而,有时不可能只使用一个表达式。在本节中,我们将看到如何将多个正则表达式连接成一个

If we are unable to create a common regular expression that can validate all the possible cases that we want to cover, we can define different expressions for each of the cases and then use them all together by concatenating them with a pipe symbol (|).

如果我们无法创建一个通用的正则表达式来验证我们想要涵盖的所有可能的情况,我们可以为每一种情况定义不同的表达式,然后通过用管道符号(|)连接它们来一起使用。

Let’s see an example where we use the following expressions:

让我们看一个例子,我们使用以下表达式。

  • The expression used in the last section:
    • ^(\\+\\d{1,3}( )?)?((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$
  • Regular expression to allow numbers like +111 123 456 789:
    • ^(\\+\\d{1,3}( )?)?(\\d{3}[ ]?){2}\\d{3}$
  • Pattern to allow numbers like +111 123 45 67 89:
    • ^(\\+\\d{1,3}( )?)?(\\d{3}[ ]?)(\\d{2}[ ]?){2}\\d{2}$
@Test
public void whenMatchesPhoneNumber_thenCorrect() {
    String patterns 
      = "^(\\+\\d{1,3}( )?)?((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$" 
      + "|^(\\+\\d{1,3}( )?)?(\\d{3}[ ]?){2}\\d{3}$" 
      + "|^(\\+\\d{1,3}( )?)?(\\d{3}[ ]?)(\\d{2}[ ]?){2}\\d{2}$";

    String[] validPhoneNumbers 
      = {"2055550125","202 555 0125", "(202) 555-0125", "+111 (202) 555-0125", 
      "636 856 789", "+111 636 856 789", "636 85 67 89", "+111 636 85 67 89"};

    Pattern pattern = Pattern.compile(patterns);
    for(String phoneNumber : validPhoneNumbers) {
        Matcher matcher = pattern.matcher(phoneNumber);
        assertTrue(matcher.matches());
    }
}

As we can see in the above example, by using the pipe symbol, we can use the three expressions in one go, thus allowing us to cover more cases than with just one regular expression.

正如我们在上面的例子中所看到的,通过使用管道符号,我们可以一次性使用三个表达式,从而使我们能够比只使用一个正则表达式覆盖更多的情况。

4. Conclusion

4.结论

In this article, we’ve seen how to check whether a String contains a valid phone number using different regular expressions. We’ve also learned how to use multiple regular expressions at the same time.

在这篇文章中,我们看到了如何使用不同的正则表达式来检查一个String是否包含一个有效的电话号码。我们还学习了如何同时使用多个正则表达式。

As always, the full source code of the article is available over on GitHub.

一如既往,文章的完整源代码可在GitHub上获得over。