【发布时间】:2011-05-31 08:22:38
【问题描述】:
MDN 说:
要执行“粘性”搜索, 从当前开始的比赛 在目标字符串中的位置,使用 y 标志。
我不太明白。
【问题讨论】:
标签: javascript regex flags
MDN 说:
要执行“粘性”搜索, 从当前开始的比赛 在目标字符串中的位置,使用 y 标志。
我不太明白。
【问题讨论】:
标签: javascript regex flags
正则表达式对象有一个lastIndex 属性,根据g (global) 和y (sticky) 标志以不同的方式使用它。 y(粘性)标志告诉正则表达式在 lastIndex 和 only 在 lastIndex(不在字符串的更早或更晚)处查找匹配项。
示例值 1024 个单词:
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 关于^ 断言有a bug in the handling of the y flag,但它在Firefox 43(有错误)和Firefox 47(没有)之间的某个地方得到了修复。非常旧的 Firefox 版本(比如 3.6)确实有 y 并且没有错误,所以这是后来发生的回归(未定义 y 标志的行为),然后得到修复。
【讨论】: