简体   繁体   中英

What would be Regex to match the following 10-digit numbers?

What would be Regex to match the following 10-digit numbers:

0108889999 //can contain nothing except 10 digits 
011 8889999 //can contain a whitespace at that place
012 888 9999 //can contain two whitespaces like that
013-8889999 // can contain one dash
014-888-9999 // can contain two dashes

If you're just looking for the regex itself, try this:

^(\d{3}(\s|\-)?){2}\d{4}$

Put slightly more legibly:

^ # start at the beginning of the line (or input)
(
    \d{3} # find three digits
    (
        \s # followed by a space
        | # OR
        \- # a hyphen
    )? # neither of which might actually be there
){2} # do this twice,
\d{4} # then find four more digits
$ # finish at the end of the line (or input)

EDIT: Oops! The above was correct, but it was also too lenient. It would match things like 01088899996 (one too many characters) because it liked the first (or the last) 10 of them. Now it's more strict (I added the ^ and $ ).

I'm assuming you want a single regex to match any of these examples:

if (preg_match('/(\d{3})[ \-]?(\d{3})[ \-]?(\d{4})/', $value, $matches)) {
    $number = $matches[1] . $matches[2] . $matches[3];
}
preg_match('/\d{3}[\s-]?\d{3}[\s-]?\d{4}/', $string);

0108889999   // true
011 8889999  // true
012 888 9999 // true
013-8889999  // true
014-888-9999 // true

To match the specific parts:

preg_match('/(\d{3})[\s-]?(\d{3})[\s-]?(\d{4}/)', $string, $matches);

echo $matches[1]; // first 3 numbers
echo $matches[2]; // next 3 numbers
echo $matches[3]; // next 4 numbers

You can try this pattern. It satisfies your requirements.

[0-9]{3}[-\\s]?[0-9]{3}[-\\s]?[0-9]{4}

Also, you can add more conditions to the last character by appending [\\s.,]+: (phone# ending with space, dot or comma)

[0-9]{3}[-\\s]?[0-9]{3}[-\\s]?[0-9]{4}[\\s.,]+

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