2011-02-15 70 views
1
[1-9]\\d{2}-[1-9]\\d{2}-\\d{4} 

[1-9]做什么?是否就像一个特定范围的整数? 我试过194-333-1111但没有验证。在正则表达式中匹配的电话号码

这是一个微不足道的问题,但花了我一个小时,仍然无法弄清楚。

任何帮助表示赞赏!由于


编辑

if (phone.matches("[1-9]\\d{2}-[1-9]\\d{2}-\\d{4}")) 
    System.out.println("Invalid phone number"); 
else 
    System.out.println("Valid input. Thank you."); 
+0

我认为你有额外的backslllashes。 – tchrist 2011-02-15 18:42:43

+0

对不起,这是在Java中完成...忘了提及 – CppLearner 2011-02-15 18:45:43

+0

@JohnWong:正如每一个答案所述,你需要避开反斜杠。将它们从双反斜杠改为单反斜杠。 – CanSpice 2011-02-15 18:48:40

回答

3

[1-9]匹配19(含)之间的字符范围。

你在哪里测试表达式,因为它确实符合你的目标字符串。然而,斜杠是逃脱的,因为它们需要在编程语言中输入。你可能用一个可以逃避你的应用程序来测试表达式。

编辑代码:

您已经扭转你的错误消息。当字符串有效时,matches()返回true,但是您正在打印它在if语句的真实部分中无效。

1

[1-9]匹配任何从1至9

给定的正则表达式的数字肯定是错误的,除非你是\\d\d和不匹配给定数由你。如果你能分辨出你想匹配的数字格式,我们可以给出更好的正则表达式。

2

下面给出的是正则表达式的解体:

[1-9] // Starts with a digit other than 0 
\d{2} // and followed by any two digits 
- // and followed by - 
[1-9] // and followed a digit other than 0 
\d{2} // and followed by any two digits 
- // and followed by - 
\d{4} // and followed by any four digits 

194-333-1111符合以上条件的正则表达式。这个问题可能与逃逸角色有关。

e.g:

public static void RegexTest() 
    { 
      Pattern p = Pattern.compile("[1-9]\\d{2}-[1-9]\\d{2}-\\d{4}"); 
      Matcher m = p.matcher("194-333-1111"); 
      boolean b = m.matches(); 
      System.out.println(b); 

    } 
1

你的正则表达式,因为它写的,可能不会做你希望它是什么。你需要首先避开反斜杠。例如,在Perl中你会使用它像:

if ($number =~ /[1-9]\d{2}-[1-9]\d{2}-\d{4}/) { 
    print "matches!\n"; 
} 

你的正则表达式,然后将分解如下:

/[1-9] # Match exactly one of the numbers 1 through 9 
\d{2} # Match exactly two digits 
-  # Match exactly one dash 
[1-9] # Match exactly one of the numbers 1 through 9 
\d{2} # Match exactly two digits 
-  # Match exactly one dash 
\d{4} # Match exactly four digits 
/x 

编辑:要告诉你如何你的正则表达式,因为它目前为作品,这是它的故障:

/[1-9] # Match exactly one of the numbers 1 through 9 
\\  # Match exactly one \ 
d{2} # Match exactly two 'd's 
-  # Match exactly one dash 
[1-9] # Match exactly one of the numbers 1 through 9 
\\  # Match exactly one \ 
d{2} # Match exactly two 'd's 
-  # Match exactly one dash 
\\  # Match exactly one \ 
d{4} # Match exactly four 'd's 
/x 

看看双反斜杠有多大的区别?

1

如果您可以依赖其他库,那么我建议您使用Google的libphonenumber开源库来验证您的电话号码。它也有验证支持。