I an trying to get a regex for a phone number with exactly 12 digits in the format: +############.
Code i am trying to use is ([+]?)\\d{12}(\\d{2})?$
but no luck.
Please help
This pattern will match exactly 12 digits after a plus sign:
/^\+\d{12}$/
What is your trailing optional (/d{2})?
component doing in your pattern?
This is the same functionality without regex:
$phone='+012345678912';
if($phone[0]=='+' && strlen($phone)==13 && is_numeric(substr($phone,1))){
echo 'valid';
}else{
echo 'invalid';
}
// displays: valid
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. 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.
I suggest you use \\+(\\d{12})
and avoid using anchors and capture groups you do not require.
^(\+)(\d{3}\s?){4}(\d{2})?$
where \\s
is a space character and ?
means optional
https://regex101.com/r/nX5XnH/3 (demo)
+012 345 678 912 (ok)
+012345 678 912 (ok)
+012 345678912 (ok)
+01234567891244 (ok)
012345678913 (no mach - missing plus sign)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.