问题描述
我正在提供以下正则表达式:^((?? \ + 27 | 27)| 0)(\ d {9})$表示南非的号码,并且只想对以+27或27或0开头的号码返回true. +27832227765、27838776654或0612323434.
I am supplying the following regex : ^((?:\+27|27)|0)(\d{9})$for number of South Africa and want to only return true for numbers that start with +27 or 27 or 0. eg; +27832227765, 27838776654 or 0612323434.
我尝试使用: regexplanet.com
和 regex测试
但是无论我输入什么(甚至是简单的正则表达式),两者都返回false.
But both return false no matter what I enter (even simple regex).
有人知道我在做什么错吗?
Anybody know what I am doing wrong?
推荐答案
在Java代码中,您需要将反斜杠加倍,并且在在线测试器中,反斜杠必须为单个.
In Java code, you need to double the backslashes, and in a online tester, the backslashes must be single.
此外,如果与String#matches
一起使用,则不必使用字符串标记的开始和结束,因为此方法需要完整的字符串匹配.
Also, it is not necessary to use start and end of string markers if used with String#matches
as this method requires a full string match.
您的Java代码如下所示:
Here is how your Java code can look like:
String rex = "(\\+?27|0)(\\d{9})";
System.out.println("+27832227765".matches(rex)); // => true
System.out.println("27838776654".matches(rex)); // => true
System.out.println("0612323434".matches(rex)); // => true
请参见 IDEONE演示
如果使用String#find
,则需要原始正则表达式中的^
和$
锚点.
If you use String#find
, you will need the ^
and $
anchors you have in the original regex.
请注意,我将((?:\+27|27)|0)
缩短为(\+?27|0)
,因为?
量词表示 1或0次出现.额外的分组在这里确实是多余的.另外,如果您不使用捕获的文本,建议将第一组变成非捕获的文本(即(?:\+?27|0)
),并从\d{9}
中删除圆括号:
Note I shortened ((?:\+27|27)|0)
to (\+?27|0)
as ?
quantifier means 1 or 0 occurrences. The extra grouping is really redundant here. Also, If you are not using captured texts, I'd suggest turning the first group into a non-capturing (i.e. (?:\+?27|0)
) and remove the round brackets from \d{9}
:
String rex = "(?:\\+?27|0)\\d{9}";
这篇关于Java正则表达式电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!