正则表达式意外结果

时间:2019-03-15 02:08:43

标签: javascript regex string

我正在尝试使用Regex检查用户输入是否仅包含0或1?但是它也接受不同的值。

inputChange = (e) => {
    console.log(/(^$)|[0,1]*/g.test(e.target.value));
};

上面的方法对于字符串'222'返回true,但是当我使用在线Regex检查器时,它说我的Regex是正确的。

1 个答案:

答案 0 :(得分:1)

  

为什么它也与其他值匹配?

[0,1]*在这里*表示匹配零个或多个时间,因此,如果值不是0 and 1,则匹配的时间是zero

因此您可以将*更改为+

/(?:^$)|^[01]+$/
    |     |__________  Matches string with only zero and one
    |     
    |________________  Match empty strings. ( Non capturing group)

console.log(/(?:^$)|^[01]+$/.test('222'))
console.log(/(?:^$)|^[01]+$/.test(''))
console.log(/(?:^$)|^[01]+$/.test('1111111 111111'))  // fails because there's a space
console.log(/(?:^$)|^[01]+$/.test('010101'))

侧面说明:-您不应在测试中使用g标志。在此处阅读why-does-a-regexp-with-global-flag-give-wrong-results