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"]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章