Vil*_*lx- 51 javascript regex compilation
我有一种情况,我希望从用户获得一个正则表达式,并针对几千个输入字符串运行它.在手册中,我发现该RegExp对象有一种.compile()方法可用于加速这种情况.但是,如果我已经在构造函数中传递了它们,为什么我必须再次将regexp字符串传递给它?也许构造函数compile()自己做?
Dan*_*Lew 87
该RegExp().compile()方法已弃用.它与构造函数基本相同,我假设它是不推荐使用的原因.你现在应该只需要使用构造函数.
换句话说,您曾经能够这样做:
var regexp = new RegExp("pattern");
regexp.compile("new pattern");
Run Code Online (Sandbox Code Playgroud)
但是现在它与简单地调用没有任何不同:
var regexp = new RegExp("pattern");
regexp = new RegExp("new pattern");
Run Code Online (Sandbox Code Playgroud)
对于Opera 11,运行RegExp.compile()实际上会导致错误.
显然,当Opera"编译"一个正则表达式时,它将re.source字符串包含在正斜杠中(例如re.source == "^(.)"变为"/^(.)/").如果你手动编译正则表达式,Opera不会识别这个事实并继续编译它(re.source变成"//^(.)//").每次编译都会产生一组额外的正斜杠,这会改变正则表达式的含义并导致错误.
如果您正在使用/,您必须首先编译您的正则表达式才能使用它,试试这个:
var regex=new RegExp('/[a-zA-Z]/')
console.log("not compiled with escape /", regex.test("ciao") )
regex.compile()
console.log("compiled", regex.test("ciao") )
var regex=new RegExp('[a-zA-Z]')
console.log("not compiled, but no escape /", regex.test("ciao") )Run Code Online (Sandbox Code Playgroud)