对数字列表进行正则表达式测试

regular expression test on list of numbers

本文关键字:正则表达式 测试 数字 列表      更新时间:2023-09-26
var str = "123456";
if (!(/^'s*'d{6,7}'s*$/.test(str)))
{
    console.log("no");
} else {
    console.log("yes!");
}

当str的长度为6,7或10时,如何将此正则表达式更改为console.log yes ?

像下面这样改变你的正则表达式,这样它就可以允许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

直接使用 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

学习更多…