我正在使用第三方JS庫。它期望一些RegExp作爲輸入,它將用於匹配字符串的部分。現在我需要在RegExp I pass中使用lookbehind,但在JS RegExp中未實現向後看。因此,作爲解決方法,我試着從正則表達式來推導:從JS衍生出RegExp
function SubRegExp(pattern, matchIndex) {
this.matchIndex = matchIndex;
this.prototype = new RegExp(pattern);
this.exec = function(s) {
return [ this.prototype.exec(s)[this.matchIndex] ];
}
}
我測試它像這樣:
var re = new SubRegExp('m(.*)', 1);
console.log(re.exec("mfoo"));
console.log("mfoo".match(re));
我得到的是:
["foo"]
["o", index: 2, input: "mfoo"]
第一輸出如預期的那樣,但我並沒有真正瞭解第二個輸出的情況。我究竟做錯了什麼?
這個答案解釋了發生了什麼,但它不能解決問題。第二次調用仍然返回整個匹配字符串作爲第一次匹配,而不僅僅是第一次匹配。 – flyx