JavaScript RegExps中'y'粘滞模式修饰符的用途是什么?

时间:2015-05-17 19:49:21

标签: javascript regex

MDN为JavaScript RegExp引入了'y'粘性标志。这是一个documentation excerpt

  

ý

     

粘;仅匹配目标字符串中此正则表达式的lastIndex属性指示的索引(并且不会尝试与任何后续索引匹配)。

还有一个例子:

var text = 'First line\nSecond line';
var regex = /(\S+) line\n?/y;

var match = regex.exec(text);
console.log(match[1]);        // prints 'First'
console.log(regex.lastIndex); // prints '11'

var match2 = regex.exec(text);
console.log(match2[1]);       // prints 'Second'
console.log(regex.lastIndex); // prints '22'

var match3 = regex.exec(text);
console.log(match3 === null); // prints 'true'

但在这种情况下, g 全局标志的使用实际上没有任何区别:

var text = 'First line\nSecond line';
var regex = /(\S+) line\n?/g;

var match = regex.exec(text);
console.log(match[1]);        // prints 'First'
console.log(regex.lastIndex); // prints '11'

var match2 = regex.exec(text);
console.log(match2[1]);       // prints 'Second'
console.log(regex.lastIndex); // prints '22'

var match3 = regex.exec(text);
console.log(match3 === null); // prints 'true'

相同的输出。所以我猜可能还有其他关于'y'标志的东西,看起来MDN的例子不是这个修饰符的真实用例,因为它似乎只是作为'g'全局修饰符的替代。

那么,对于这个实验性的“y”粘性标志,它可能是一个真实用例吗? “仅与RegExp.lastIndex属性匹配”的目的是什么?与RegExp.prototype.exec一起使用时与“g”的区别是什么?

感谢您的关注。

2 个答案:

答案 0 :(得分:7)

yg之间的差异Practical Modern JavaScript中有描述:

  

只有找到匹配项时,粘性标记会提升lastIndex,如g,但   从lastIndex开始,没有向前搜索。添加了粘性标记以提高编写词法分析器的性能   JavaScript ......

至于真实用例,

  

可以使用从位置n开始要求正则表达式匹配,其中n   是lastIndex设置为的内容。在非多线常规的情况下   表达式,lastIndex值为0,其中包含粘性标记   效果与使用^开始正则表达式相同   要求匹配从搜索文本的开头开始。

以下是该博客的示例,其中lastIndex属性在test方法调用之前被操纵,从而强制执行不同的匹配结果:

var searchStrings, stickyRegexp;

stickyRegexp = /foo/y;

searchStrings = [
    "foo",
    " foo",
    "  foo",
];
searchStrings.forEach(function(text, index) {
    stickyRegexp.lastIndex = 1;
    console.log("found a match at", index, ":", stickyRegexp.test(text));
});

结果:

"found a match at" 0 ":" false
"found a match at" 1 ":" true
"found a match at" 2 ":" false

答案 1 :(得分:2)

行为肯定存在差异,如下所示:

insert into employee select 1,'Me',1,2400;
update employee set salary = 2800 where id = 1;

Select @delta;

..但我还没有完全理解那里发生了什么。