简体   繁体   English

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

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

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

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. 它将匹配01088899996类的01088899996 (一个字符太多),因为它喜欢其中的前10个(或最后10个字符)。 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} [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) 另外,您可以通过附加[\\ s。,] +:将更多条件添加到最后一个字符(电话号码以空格,点或逗号结尾)

[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