在下面的代码中,我试图让输出成为电话号码的不同格式,以及它是否有效。除了第 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");
}
}
}
}
原文由 Ducky 发布,翻译遵循 CC BY-SA 4.0 许可协议
基本上,您需要采用 3 或 4 种不同的模式并将它们与“|”组合:
\d{10}
匹配1234567890(?:\d{3}-){2}\d{4}
匹配123-456-7890\(\d{3}\)\d{3}-?\d{4}
匹配 (123)456-7890 或 (123)4567890