意外的Javascript RegExp行为 [英] Unexpected Javascript RegExp behavior
问题描述
我创建了一个RegExp对象(在JavaScript中)来测试数字是否存在:
I create a RegExp object (in JavaScript) to test for the presence of a number:
var test = new RegExp( '[0-9]', 'g' );
我这样使用它
console.log( test.test( '0' ) ); // true
console.log( test.test( '1' ) ); // false - why?
这个输出更令人困惑:
The output of this is even more confusing:
console.log( test.test( '1' ) ); // true
console.log( test.test( '0' ) ); // false - why?
console.log( test.test( '1' ) ); // true
console.log( test.test( '2' ) ); // false - why?
console.log( test.test( '2' ) ); // true - correct, but why is this one true?
如果我删除 g
限定符,行为如预期。
If I remove the g
qualifier, it behaves as expected.
这是一个错误,因为我相信它,或者spec的一些特殊部分?是否应该以这种方式使用 g
限定符? (我在多个任务中重复使用同一个表达式,因此具有限定符)
Is this a bug as I believe it is, or some peculiar part of the spec? Is the g
qualifier supposed to be used this way? (I'm re-using the same expression for multiple tasks, hence having the qualifier at all)
推荐答案
a href =https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp/test#Description> https://developer.mozilla.org/en-US/docs/JavaScript / Reference / Global_Objects / RegExp / test#Description
Per documentation: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp/test#Description
test
在同一个全局正则表达式实例中调用多次将超过前一次匹配。
test
called multiple times on the same global regular expression instance will advance past the previous match.
您可以确认此行为:
var test = new RegExp( '[0-9]', 'g' );
test.test('01'); //true
test.test('01'); //true
test.test('01'); //false
使用 g
标志,如果你想要的是确认与各种字符串的单一匹配。
It doesn't make sense to use the g
flag if all you want is to confirm a single match against various strings.
这篇关于意外的Javascript RegExp行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!