簡體   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