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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42104546/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:55:23  来源:igfitidea点击:

Java Regular Expressions to Validate phone numbers

javaregex

提问by Ducky

In the following code I am trying to get the output to be the different formatting of phone numbers and if it is either valid or not. I figured everything out but the Java Regular Expression code on line 11 the string pattern.

在下面的代码中,我试图让输出成为电话号码的不同格式,以及它是否有效。我想出了一切,但第 11 行的 Java 正则表达式代码是字符串模式。

 import java.util.regex.*;

  public class MatchPhoneNumbers {
   public static void main(String[] args) {           
     String[] testStrings = {               
               /* Following are valid phone number examples */             
              "(123)4567890", "1234567890", "123-456-7890", "(123)456-7890",
              /* Following are invalid phone numbers */ 
              "(1234567890)","123)4567890", "12345678901", "(1)234567890",
              "(123)-4567890", "1", "12-3456-7890", "123-4567", "Hello world"};

             // TODO: Modify the following line. Use your regular expression here
              String pattern = "^/d(?:-/d{3}){3}/d$";    
             // current pattern recognizes any string of digits           
             // Apply regular expression to each test string           
             for(String inputString : testStrings) {
                System.out.print(inputString + ": "); 
                if (inputString.matches(pattern)) {     
                    System.out.println("Valid"); 
                } else {     
                    System.out.println("Invalid"); 
                }
             }
      }
  }

采纳答案by Patrick Parker

Basically, you need to take 3 or 4 different patterns and combine them with "|":

基本上,您需要采用 3 或 4 种不同的模式并将它们与“|”组合在一起:

String pattern = "\d{10}|(?:\d{3}-){2}\d{4}|\(\d{3}\)\d{3}-?\d{4}";
  • \d{10}matches 1234567890
  • (?:\d{3}-){2}\d{4}matches 123-456-7890
  • \(\d{3}\)\d{3}-?\d{4}matches (123)456-7890 or (123)4567890
  • \d{10}匹配 1234567890
  • (?:\d{3}-){2}\d{4}匹配 123-456-7890
  • \(\d{3}\)\d{3}-?\d{4}匹配 (123)456-7890 或 (123)4567890

回答by Elliott Frisch

Create a non-capturing group for three digits in parenthesis orthree digits (with an optional dash). Then you need three digits (with another optional dash), followed by four digits. Like, (?:\\(\\d{3}\\)|\\d{3}[-]*)\\d{3}[-]*\\d{4}. And you might use a Pattern. All together like,

为括号中的三位数字三位数字(带有可选的破折号)创建一个非捕获组。然后你需要三个数字(另一个可选的破折号),然后是四个数字。喜欢,(?:\\(\\d{3}\\)|\\d{3}[-]*)\\d{3}[-]*\\d{4}。你可能会使用一个Pattern. 大家一起喜欢,

String[] testStrings = {
        /* Following are valid phone number examples */         
        "(123)4567890", "1234567890", "123-456-7890", "(123)456-7890",
        /* Following are invalid phone numbers */
        "(1234567890)","123)4567890", "12345678901", "(1)234567890",
        "(123)-4567890", "1", "12-3456-7890", "123-4567", "Hello world"};

Pattern p = Pattern.compile("(?:\(\d{3}\)|\d{3}[-]*)\d{3}[-]*\d{4}");
for (String str : testStrings) {
    if (p.matcher(str).matches()) {
        System.out.printf("%s is valid%n", str);
    } else {
        System.out.printf("%s is not valid%n", str);    
    }
}

回答by ankit MISHRA

The regex that you need is:

您需要的正则表达式是:

String regEx = "^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$";

Regex explanation:

正则表达式解释:

^\\(?- May start with an option "("

^\\(?- 可以以选项“(”开头

(\\d{3})- Followed by 3 digits

(\\d{3})- 后跟 3 位数字

\\)?- May have an optional ")"

\\)?- 可能有一个可选的“)”

[- ]?- May have an optional "-" after the first 3 digits or after optional ) character

[- ]?- 在前 3 位数字或可选的 ) 字符之后可能有一个可选的“-”

(\\d{3})- Followed by 3 digits.

(\\d{3})- 后跟 3 位数字。

[- ]?- May have another optional "-" after numeric digits

[- ]?- 数字后可能有另一个可选的“-”

(\\d{4})$- ends with four digits

(\\d{4})$- 以四位数结尾

回答by Anurag Gupta

international phone number regex

国际电话号码正则表达式

String str=  "^\s?((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?\s?";


 if (Pattern.compile(str).matcher(" +33 - 123 456 789 ").matches()) {
        System.out.println("yes");
    } else {
        System.out.println("no");
    } 

回答by Ashish Lahoti

Considering these facts about phone number format:-

考虑到有关电话号码格式的这些事实:-

  1. Country Code prefix starts with ‘+' and has 1 to 3 digits
  2. Last part of the number, also known as subscriber number is 4 digits in all of the numbers
  3. Most of the countries have 10 digits phone number after excluding country code. A general observation is that all countries phone number falls somewhere between 8 to 11 digits after excluding country code.
  1. 国家/地区代码前缀以“+”开头,包含 1 到 3 位数字
  2. 号码的最后一部分,也称为订户号码,是所有号码中的 4 位数字
  3. 大多数国家/地区在排除国家/地区代码后都有 10 位电话号码。一般观察是,所有国家/地区的电话号码在排除国家/地区代码后都介于 8 到 11 位数字之间。
String allCountryRegex = "^(\+\d{1,3}( )?)?((\(\d{1,3}\))|\d{1,3})[- .]?\d{3,4}[- .]?\d{4}$";

Let's break the regex and understand,

让我们打破正则表达式并理解,

  • ^start of expression
  • (\\+\\d{1,3}( )?)?is optional match of country code between 1 to 3 digits prefixed with '+' symbol, followed by space or no space.
  • ((\\(\\d{1,3}\\))|\\d{1,3}is mandatory group of 1 to 3 digits with or without parenthesis followed by hyphen, space or no space.
  • \\d{3,4}[- .]?is mandatory group of 3 or 4 digits followed by hyphen, space or no space
  • \\d{4}is mandatory group of last 4 digits
  • $end of expression
  • ^表达的开始
  • (\\+\\d{1,3}( )?)?是 1 到 3 位数字之间的国家代码的可选匹配,前缀为“+”符号,后跟空格或无空格。
  • ((\\(\\d{1,3}\\))|\\d{1,3}是由 1 到 3 位数字组成的强制性组,带或不带括号,后跟连字符、空格或不带空格。
  • \\d{3,4}[- .]?是由 3 或 4 位数字组成的强制性组,后跟连字符、空格或无空格
  • \\d{4}是最后 4 位数字的强制性组
  • $表达结束

This regex pattern matches most of the countries phone number format including these:-

此正则表达式模式匹配大多数国家/地区的电话号码格式,包括:-

        String Afghanistan      = "+93 30 539-0605";
        String Australia        = "+61 2 1255-3456";
        String China            = "+86 (20) 1255-3456";
        String Germany          = "+49 351 125-3456";
        String India            = "+91 9876543210";
        String Indonesia        = "+62 21 6539-0605";
        String Iran             = "+98 (515) 539-0605";
        String Italy            = "+39 06 5398-0605";
        String NewZealand       = "+64 3 539-0605";
        String Philippines      = "+63 35 539-0605";
        String Singapore        = "+65 6396 0605";
        String Thailand         = "+66 2 123 4567";
        String UK               = "+44 141 222-3344";
        String USA              = "+1 (212) 555-3456";
        String Vietnam          = "+84 35 539-0605";

Source:https://codingnconcepts.com/java/java-regex-for-phone-number/

来源:https: //codingnconcepts.com/java/java-regex-for-phone-number/