我必须编写一个正则表达式,以下列格式验证美国电话号码:
(123).123.1234 -- true
1234567890 -- true
(123)1231234 -- true
(123)-456-7890 -- true
(123) 123 1234 -- true
123 123 1234 -- true
(123). 456. 7890 -- true
(123)- 456- 7890 -- true.
我想出了类似的东西:
[\\(]?\\d{3}[\\)]?[-.]?[\\s]*\\d{3}[-.]?[\\s]*\\d{4}
不幸的是,根据我的正则表达式,下面的值也是有效的:
123.123-1234
(123)-123.1234
123. 123- 1234
答案 0 :(得分:1)
您可以使用以下正则表达式匹配这些数字:
div
请参阅IDEONE demo
String rx = "[\\(]?\\d{3}[\\)]?([-.]?)\\s*\\d{3}\\1\\s*\\d{4}";
构造是capturing group 捕获并将匹配的文本存储在某个缓冲区中,然后我们可以使用([-.]?)
{{访问该文本3}}以后。
请注意,如果您需要整个字符串匹配,请使用\\1
方法和正则表达式。
答案 1 :(得分:0)
为此,您需要使用捕获组和后退。
\\(?\\d{3}\\)?([-.]?[\\s]*)\\d{3}\\1\\d{4}
必要时添加锚点。
^\\(?\\d{3}\\)?([-.]?[\\s]*)\\d{3}\\1\\d{4}$
答案 2 :(得分:0)
你可以试试这个。你会得到所有类型的电话号码。
public static void contact(String line, HashSet<String> hs) {
Pattern pattern = Pattern.compile("(\\d{1}\\s\\d{2}\\s\\d{8})"
+ "|"
+ "(\\d{2}\\s\\d{2}\\s\\d{8})"
+ "|"
+ "(\\(\\d{3}\\)\\s\\d{3}-\\d{4})"
+ "|"
+ "(\\d{1}\\s\\(\\d{3}\\)\\s\\d{3}-\\d{4})"
+ "|"
+ "(\\d{1}\\s\\(\\d{3}\\)\\s\\d{3}\\s\\d{4})"
+ "|"
+ "(\\d{2}\\s\\(\\d{3}\\)\\s\\d{3}\\s\\d{4})"
+ "|"
+ "(\\d{2}\\s\\(\\d{3}\\)\\s\\d{3}-\\d{4})"
+ "|"
+ "(\\(\\d{2}\\)\\-\\d{10})"
+ "|"
+ "(\\(\\d{2}\\)\\s\\d{10})"
+ "|"
+ "(\\(\\d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
+ "(\\d{3}-\\d{8})"
+ "|"
+ "(\\d{3}-\\d{2}-\\d{5})"
+ "|"
+ "(\\d{2}\\s\\d{2}\\s\\d{4}-\\d{4})"
+ "|"
+ "(\\d{2}\\-\\d{2}\\. ISSN \\d{4}-\\d{4})"
+ "|"
+ "(\\d{4}\\-\\d{4}\\-\\d{1}-\\d{3})"
+ "|"
+ "(\\d{2}\\s\\d{4}\\s\\d{4})"
+ "|"
+ "(\\d{3}\\s\\d{1}\\s\\d{7})"
+ "|"
+ "(\\d{13})"
+ "|"
+ "(\\d{12})"
+ "|"
+ "(\\d{11})"
+ "|"
+ "(\\d{10})"
+ "|"
+ "(\\d{9})"
+ "|"
+ "(\\d{2}\\s\\d{10})"
+ "|"
+ "(\\d{1}\\s\\d{10})"
+ "|"
+ "(^(?:(?:\\+?1\\s*(?:[.-]\\s*)?)?(?:\\(\\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\\s*\\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\\s*(?:[.-]\\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\\s*(?:[.-]\\s*)?([0-9]{4})(?:\\s*(?:#|x\\.?|ext\\.?|extension)\\s*(\\d+))?$)");
Matcher m = pattern.matcher(line);
while(m.find()) {
System.out.println("Contact Number---->"+"'"+m.group(0)+"'");
}