用于validation电话号码的Java正则表达式

在下面的代码中,我试图让输出为电话号码的不同格式,如果它是有效的。 我想出了一切,但第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"); } } } } 

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

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

在括号中创建三个数字的非捕获组三个数字(使用可选的破折号)。 然后你需要三个数字(另一个可选的破折号),然后是四个数字。 比如, (?:\\(\\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); } } 

你需要的正则表达式是:

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

正则表达式解释:

^\\(? – 可以选项“(”

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

\\)? – 可以选择“)”

[- ]? – 可以在前3个数字后或可选后的字符后面添加一个“ – ”

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

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

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