简体   繁体   中英

12 digit Regex for Phone number

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

Try this:

^\+\d{12}(\d{2})?$

You needed to escape the plus sign

Regex101 Demo

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:

  1. You're only capturing the + sign and the 2 digits after the initial 12.

  2. You anchor to the end of the string and not the beginning
  3. Both the + and 2 extra numerals are optional but you wanted to get the +############ exact?

I suggest you use \\+(\\d{12}) and avoid using anchors and capture groups you do not require.

If you want to support optional spaces between sets of three numbers, you would use this regex instead

^(\+)(\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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM