用于验证电话号码的Java正则表达式 [英] Java Regular Expressions to Validate phone numbers
本文介绍了用于验证电话号码的Java正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在下面的代码中,我试图让输出为电话号码的不同格式,如果它有效或无效。我想出了一切,但第11行的Java正则表达式代码是字符串模式。
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.
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种不同的模式并将它们与|组合:
Basically, you need to take 3 or 4 different patterns and combine them with "|":
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} \)\\\ {3} - ?\d {4}
匹配(123)456-7890或(123)4567890 \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
这篇关于用于验证电话号码的Java正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文