【问题标题】:What does regex' flag 'y' do?正则表达式'标志'y'做什么?
【发布时间】:2011-05-31 08:22:38
【问题描述】:

MDN 说:

要执行“粘性”搜索, 从当前开始的比赛 在目标字符串中的位置,使用 y 标志。

我不太明白。

【问题讨论】:

    标签: javascript regex flags


    【解决方案1】:

    正则表达式对象有一个lastIndex 属性,根据g (global) 和y (sticky) 标志以不同的方式使用它。 y(粘性)标志告诉正则表达式在 lastIndexonlylastIndex(不在字符串的更早或更晚)处查找匹配项。

    示例值 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 标志的行为),然后得到修复。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-17
      • 2011-10-24
      • 1970-01-01
      • 1970-01-01
      • 2022-12-17
      • 2010-12-17
      相关资源
      最近更新 更多