[英]Unexpected behavior of regexp in JavaScript
我遇到了这种奇怪的行为:
我在断点上(变量不变)。 在控制台上,您可以看到,每次我尝试在相同的不变变量“文本”上评估regexp方法时,都会得到这些相反的响应。 这样的事情有解释吗?
相关代码在这里:
this.singleRe = /<\$([\s\S]*?)>/g;
while( this.singleRe.test( text ) ){
match = this.singleRe.exec( text );
result = "";
if( match ){
result = match[ 1 ].indexOf( "." ) != -1 ? eval( "obj." + match[ 1 ] ) : eval( "value." + match[ 1 ] );
}
text = text.replace( this.singleRe , result );
}
当您将regex与exec()
和全局标志 g
,每次都会更改光标,如下所示:
var re = /\w/g;
var s = 'Hello regex world!'
re.exec(s); // => ['H']
re.exec(s); // => ['e']
re.exec(s); // => ['l']
re.exec(s); // => ['l']
re.exec(s); // => ['o']
注意g
标志! 这意味着正则表达式将匹配多次出现而不是一次!
编辑
如果可能的话,我建议不要使用regex.exec(string)
来使用string.match(regex)
。 这将产生一个数组,并且很容易检查数组或遍历数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.