正则表达式'标志'是什么? [英] What does regex' flag 'y' do?

查看:101
本文介绍了正则表达式'标志'是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MDN说:


要执行粘性搜索,
匹配从当前
开始在目标字符串中的位置,使用
y flag。

To perform a "sticky" search, that matches starting at the current position in the target string, use the y flag.

我不太明白。

推荐答案

正则表达式对象具有 lastIndex 属性,该属性以不同方式使用,具体取决于 g (全局)和 y (粘性)标志。 y (粘性)标志告诉正则表达式在 lastIndex at lastIndex (不在字符串的前面或后面)。

Regular expression objects have a lastIndex property, which is used in different ways depending on the g (global) and y (sticky) flags. The y (sticky) flag tells the regular expression to look for a match at lastIndex and only at lastIndex (not earlier or later in the string).

示例值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已经处理的错误y 标志关于 ^ 断言,但它在Firefox 43(有bug)和Firefox 47之间修复(没有)。很老版本的Firefox(比如3.6)确实有 y 并且没有错误,所以这是后来发生的回归(未定义<$的行为) c $ c> y flag),然后得到修复。

Firefox's SpiderMonkey JavaScript engine has had the y flag for years, but it wasn't part of the specification until ES2015 (June 2015). Also, for quite a while Firefox had a bug in the handling of the y flag with regard to the ^ assertion, but it was fixed somewhere between Firefox 43 (has the bug) and Firefox 47 (doesn't). Very old versions of Firefox (say, 3.6) did have y and didn't have the bug, so it was a regression that happened later (not defined behavior for the y flag), and then got fixed.

这篇关于正则表达式'标志'是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆