正则表达式的旗帜'y'是什么作用?

50

MDN说:

使用y标志进行“粘滞”搜索,从目标字符串中当前位置开始匹配。

我不太理解它的意思。

1个回答

65
正则表达式对象有一个lastIndex属性,具体使用方式取决于g (global)和y (sticky)标志。 y (sticky) 标志告诉正则表达式在lastIndex处寻找匹配,并且仅仅在字符串中的lastIndex位置(不是更早或更晚)进行匹配。

举个例子,胜过千言万语:

var str =  "a0bc1";
// Indexes: 01234

var rexWithout = /\d/;
var rexWith    = /\d/y;

// Without:
rexWithout.lastIndex = 2;          // (This is a no-op, because the regex
                                   // doesn't have either g or y.)
console.log(rexWithout.exec(str)); // ["0"], found at index 1, because without
                                   // the g or y flag, the search is always from
                                   // index 0

// With, unsuccessful:
rexWith.lastIndex = 2;             // Says to *only* match at index 2.
console.log(rexWith.exec(str));    // => null, there's no match at index 2,
                                   // only earlier (index 1) or later (index 4)

// With, successful:
rexWith.lastIndex = 1;             // Says to *only* match at index 1.
console.log(rexWith.exec(str));    // => ["0"], there was a match at index 1.

// With, successful again:
rexWith.lastIndex = 4;             // Says to *only* match at index 4.
console.log(rexWith.exec(str));    // => ["1"], there was a match at index 4.
.as-console-wrapper {
  max-height: 100% !important;
}


兼容性提示:

Firefox的SpiderMonkey JavaScript引擎多年来一直有y标志,但直到ES2015(2015年6月)才成为规范的一部分。此外,Firefox在处理y标志与^断言有关时长时间出现错误的情况,但在Firefox 43(存在该错误)和Firefox 47(不存在该错误)之间得到了修复。很早之前的Firefox版本(例如3.6)具有y,没有这个错误,所以它是后来发生的回归(不定义y标志的行为),然后被修复。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接