繁体   English   中英

匹配以下10位数字的正则表达式是什么?

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

什么是正则表达式以匹配以下10位数字:

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

如果您只是在寻找正则表达式本身,请尝试以下操作:

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

清楚一点:

^ # 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)

编辑:糟糕! 以上是正确的,但也太宽容了。 它将匹配01088899996类的01088899996 (一个字符太多),因为它喜欢其中的前10个(或最后10个字符)。 现在更加严格了(我添加了^$ )。

我假设您希望单个正则表达式匹配以下任何示例:

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

要匹配特定部分:

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

您可以尝试这种模式。 满足您的要求。

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

另外,您可以通过附加[\\ s。,] +:将更多条件添加到最后一个字符(电话号码以空格,点或逗号结尾)

[0-9] {3} [ - \\ S] [0-9] {3} [ - \\ S] [0-9] {4} [\\ S,] +

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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