我正在使用第三方 JS 库。它需要一些 RegExp 作为输入,用于匹配字符串的各个部分。现在我需要在我传递的RegExp中使用lookbehind,但是lookbehind在JS RegExp中没有实现。因此,作为解决方法,我尝试从 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"]
第一个输出符合预期,但我并没有真正了解第二个输出发生了什么。我做错了什么?
最佳答案
为了使 String.prototype.match
函数与您的自定义类实例一起使用,您应该实现一个 toString
方法,该方法返回正则表达式字符串。
function SubRegExp(pattern, matchIndex) {
this.pattern = pattern;
this.matchIndex = matchIndex;
this.rgx = new RegExp(pattern);
this.exec = function(s) {
return [ this.rgx.exec(s)[this.matchIndex] ];
}
}
SubRegExp.prototype.toString = function(){
return this.pattern;
}
var re = new SubRegExp('m(.*)', 1);
console.log(re.exec('mfoo'));
console.log('mfoo'.match(re));
//-> ["foo"]
//-> ["mfoo", "foo", index: 0, input: "mfoo"]
解释您的示例中发生的情况,以及为什么会得到 'o'
结果。实际上,这是非常有趣的巧合 - 'mfoo'.match(re)
将 re
实例转换为字符串,然后将其用作正则表达式模式。 re.toString() === "[object Object]"
。
"[object Object]"
- 这是正则表达式中的一个组,这就是匹配第一个 'o'
的原因:)
编辑
抱歉,没有太注意第二个输出。 .match()
不会调用您的自定义 exec
函数,因为使用了原始正则表达式字符串(来自 toString
的,正如我所言解释了)。唯一的出路是重写 match
函数,尽管这不是一个好的做法。
(function(){
var original = String.prototype.match;
String.prototype.match = function(mix) {
if (mix instanceof SubRegExp)
return mix.exec(this);
return original.call(this, mix);
}
}());
关于javascript - 源自 JS RegExp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19573239/