七.增强正则表达式
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"]