[英]12 digit Regex for Phone number
I an trying to get a regex for a phone number with exactly 12 digits in the format: +############. 我试图获取一个正则表达式,用于正好为12位数字的电话号码,格式为:+ ############。
Code i am trying to use is ([+]?)\\d{12}(\\d{2})?$
but no luck. 我尝试使用的代码是
([+]?)\\d{12}(\\d{2})?$
但是没有运气。
Please help 请帮忙
This pattern will match exactly 12 digits after a plus sign: 此模式将与加号后的12位数字完全匹配:
/^\+\d{12}$/
What is your trailing optional (/d{2})?
您尾随的可选内容
(/d{2})?
component doing in your pattern? 组件在您的模式中做什么?
This is the same functionality without regex: 这是没有regex的相同功能:
$phone='+012345678912';
if($phone[0]=='+' && strlen($phone)==13 && is_numeric(substr($phone,1))){
echo 'valid';
}else{
echo 'invalid';
}
// displays: valid
Try this: 尝试这个:
^\+\d{12}(\d{2})?$
You needed to escape the plus sign 您需要转义加号
Do we need to capture certain digits/sequences or are you just validating its a number with that format? 我们是否需要捕获某些数字/序列,或者您只是使用该格式验证其数字?
I use this online tool regex101 whenever I'm unsure of regex. 每当我不确定regex时,都会使用此在线工具regex101 。 It shows on the right exactly what you're capturing/checking which is very useful.
它会在右侧准确显示您正在捕获/检查的内容,这非常有用。 Depending on your use case, I don't see how this regex doesn't work, please provide an example.
根据您的用例,我看不到此正则表达式如何工作,请提供示例。 Otherwise:
除此以外:
You're only capturing the + sign and the 2 digits after the initial 12. 您只捕获了前12个字母后的+号和2位数字。
I suggest you use \\+(\\d{12})
and avoid using anchors and capture groups you do not require. 建议您使用
\\+(\\d{12})
并避免使用不需要的锚点和捕获组。
^(\+)(\d{3}\s?){4}(\d{2})?$
where \\s
is a space character and ?
\\s
是空格字符,而?
means optional 表示可选
https://regex101.com/r/nX5XnH/3 (demo) https://regex101.com/r/nX5XnH/3 (演示)
+012 345 678 912 (ok)
+012345 678 912 (ok)
+012 345678912 (ok)
+01234567891244 (ok)
012345678913 (no mach - missing plus sign)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.