我正在尝试在类似
的字符串上运行正则表达式 string = 'The value is ij35dss. The value is fsd53fdsfds.'
我想要的地方string.match(/The value is (.*?)\./g);
仅返回['ijdss','fsdfdsfds']
而非['The value is ijdss.', 'The value is fsdfdsfds.']
答案 0 :(得分:4)
使用RegExp.exec
代替,这是一个示例:
var string = 'The value is ij35dss. The value is fsd53fdsfds.';
var re = new RegExp(/The value is (.*?)\./g)
var strs = []
var m = re.exec(string)
while(m != null) {
strs.push(m[1]);
m = re.exec(string)
}
alert(strs)
和jsFiddle:
如果您认为经常需要这个,可以将其添加到String.prototype:
String.prototype.matchGroup = function(re, group) {
var m = re.exec(string);
var strs = [];
while(m != null) {
strs.push(m[group]);
m = re.exec(string);
}
return strs;
}
var string = 'The value is ij35dss. The value is fsd53fdsfds.';
alert(string.matchGroup(/The value is (.*?)\./g, 1));
的jsfiddle:
现金: