2014-12-29 38 views
-1

我需要字符串这是两个字符串之间,但是当我使用str.match结果的阵列之间的每个字符串是不是我所期望:给出的字符串

var text = "first second1 third\nfirst second2 third\nfirst second3 third"; 
var middles = text.match(/first (.*?) third/g); 
console.log(middles); //this should be ["second1", "second2", "second3"] 

结果:

["first second1 third", "first second2 third", "first second3 third"] 

有什么我可以尝试只获得每个事件的中间字符串?

+1

这将是如此容易得多,如果使用Javascript支持的回顾后。那么你可以做'/(?= first)*?(?= third)/ g' –

+0

/(?= first)(。*)(?= third)/ g这个工作,但仍然包含第一个 – shuji

回答

1

从文档RegExp.prototype.exec()

如果你的正则表达式使用“G”标志,你可以使用exec 方法多次找到相同的字符串匹配连续。 当您这样做时,搜索将从 正则表达式的lastIndex属性(test()也将提前 lastIndex属性)指定的str的子字符串开始。

将此应用于您的情况:

var text = "first second1 third\nfirst second2 third\nfirst second3 third"; 
var middles = [], md, regex = /first (.*?) third/g; 

while(md = regex.exec(text)) { middles.push(md[1]); } 

middles // ["second1", "second2", "second3"] 
相关问题