我正在 JavaScript 中创建一个正则表达式,它应该查找数字(至少 1)和字母(至少 1),总长度在 6 到 10 之间。我遇到了一些意想不到的行为。
我的正则表达式 - /^[a-z+\d+]{6,10}$/g
。
这不能正常工作,因为在字符类中,它会检查字母或数字,但不会同时检查两者。因此,我预计 "123456"
会失败,因为虽然它包含 6 个字符,并且至少有 1 个数字,但它不包含 1 个字母。
但是,在下面的代码片段中,当我将正则表达式存储在 rgx
变量中并对其使用 .test()
时,它以某种方式正确返回 false
,如第二个 console.log
语句所示。但在下一行,当我直接将正则表达式与 .test()
使用时,它返回 true
。
let rgx = /^[a-z+\d+]{6,10}$/g;
// works fine
console.log(rgx.test("abcd12"));
// returns false
console.log(rgx.test("123456"));
// same regex returns true
console.log(/^[a-z+\d+]{6,10}$/g.test("123456"));
这是怎么回事?
最佳答案
尝试
let rgx = /^[a-z+\d+]{6,10}$/g;
let rgx2 = /^[a-z+\d+]{6,10}$/g;
console.log(rgx.test("abcd12")); //true
console.log(rgx2.test("123456")); //true
因为
Javascript RegExp object is stateful i.e. if you re-use a RegExp object (with 'g' flag set), subsequent matches would start from the end of the last match.
关于JavaScript 正则表达式 .test() 的意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47120206/