什么是正则表达式匹配以下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
Run Code Online (Sandbox Code Playgroud)
如果你只是在寻找正则表达式本身,试试这个:
^(\d{3}(\s|\-)?){2}\d{4}$
Run Code Online (Sandbox Code Playgroud)
稍微放一点:
^ # 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)
Run Code Online (Sandbox Code Playgroud)
编辑:哎呀!以上是正确的,但它也太宽松了.它会匹配01088899996(一个太多的字符)之类的东西,因为它喜欢它们的第一个(或最后一个)10个.现在它更严格(我添加了^和$).