ECMAScript 6(ES6) 特性概览和与ES5的比较7-增强正则表达式

七.增强正则表达式

1. 正则表达式粘性匹配

在匹配之间保持匹配位置粘滞,这种方式支持对任意长输入字符串的有效解析,即使使用任意数量的不同正则表达式也是如此。(看不懂)
ECMAScript 6

let parser = (input, match) => {
   for (let pos = 0, lastPos = input.length; pos < lastPos;) {
      for (let i = 0; i < match.length; i++) {
          match[i].pattern.lastIndex = pos
          let found
          if ((found = match[i].pattern.exec(input)) !== null) {
              match[i].action(found)
              pos = match[i].pattern.lastIndex
              break
          }
      }
   }
}
let report = (match) => {
    console.log(JSON.stringify(match))
}
parser("Foo 1 Bar 7 Baz 42",[
    { pattern: /Foo\s+(\d+)/y, action: (match) => report(match) },
    { pattern: /Bar\s+(\d+)/y, action: (match) => report(match) },
    { pattern: /Baz\s+(\d+)/y, action: (match) => report(match) },
    { pattern: /\s*/y,         action: (match) => {}            }
])
//["Foo 1","1"]
//["Bar 7","7"]
//["Baz 42","42"]

ECMAScript 5

var parser = function (input, match) {
    for (var i, found, inputTmp = input; inputTmp !== ""; ) {
        for (i = 0; i < match.length; i++) {
            if ((found = match[i].pattern.exec(inputTmp)) !== null) {
                match[i].action(found);
                inputTmp = inputTmp.substr(found[0].length);
                break;
            }
        }
    }
}

var report = function (match) {
    console.log(JSON.stringify(match));
};
parser("Foo 1 Bar 7 Baz 42", [
    { pattern: /^Foo\s+(\d+)/, action: function (match) { report(match); } },
    { pattern: /^Bar\s+(\d+)/, action: function (match) { report(match); } },
    { pattern: /^Baz\s+(\d+)/, action: function (match) { report(match); } },
    { pattern: /^\s*/,         action: function (match) {}                 }
]);
//["Foo 1","1"]
//["Bar 7","7"]
//["Baz 42","42"]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值