2014-12-29 94 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"] 
相關問題