var str = "123456";
if (!(/^\s*\d{6,7}\s*$/.test(str)))
{
console.log("no");
} else {
console.log("yes!");
}
当str的长度为6,7或10时,如何将此正则表达式更改为console.log是仅?
答案 0 :(得分:5)
如下所示更改正则表达式,以便允许带有可选前导和尾随空格的6或7或10位数字。
^\s*(?:\d{10}|\d{6,7})\s*$
<强>代码:强>
> var str = "1234567890";
undefined
> if (!(/^\s*(?:\d{10}|\d{6,7})\s*$/.test(str)))
... {
... console.log("no");
... } else {
... console.log("yes!");
... }
yes!
<强>解释强>
^ the beginning of the string
\s* whitespace (\n, \r, \t, \f, and " ") (0 or
more times)
(?: group, but do not capture:
\d{10} digits (0-9) (10 times)
| OR
\d{6,7} digits (0-9) (between 6 and 7 times)
) end of grouping
\s* whitespace (\n, \r, \t, \f, and " ") (0 or
more times)
$ before an optional \n, and the end of the
string
答案 1 :(得分:0)
只需尝试 OR ing。
^\s*(\d{6,7}|\d{10})\s*$
模式说明:
^ the beginning of the string
\s* whitespace (\n, \r, \t, \f, and " ") (0 or more times)
( group and capture to \1:
\d{6,7} digits (0-9) (between 6 and 7 times)
| OR
\d{10} digits (0-9) (10 times)
) end of \1
\s* whitespace (\n, \r, \t, \f, and " ") (0 or more times)
$ the end of the string