返回Null之前的regexp exec模式

时间:2011-06-21 15:27:55

标签: javascript regex

我的测试RegExp with pattern before返回null。如何让它返回2?

s = new RegExp(/(?=ID\=)(\d+)/).exec("ID=2");

3 个答案:

答案 0 :(得分:3)

(?=)是一个先行断言。你想使用lookbehind,JavaScript不支持。但是,这样可以正常工作:

s = /ID=(\d+)/.exec('ID=2')[1];
// or
s = new RegExp('ID=(\\d+)').exec('ID=2')[1];

不要将正则表达式文字传递给RegExp构造函数 - 这是没有意义的。

但是,真的,你为什么不分开=

s = 'ID=2'.split('=')[1];

答案 1 :(得分:0)

如果您只想提取数字部分,请尝试关注..

"ID=2".match(/\d+/)[0]

只是

"ID=2".match(/\d+/)

答案 2 :(得分:0)

if("ID=2".match(new RegExp(/ID\=(\d+)/)))
    alert("Matched" + RegExp.$1);
else
    alert("No Match");

试试吧!

您需要使用String.match()

相关问题