2015-01-21 119 views
1

我是新的正則表達式。我需要提取兩個字符串模式([[tag :: & ]])以及每次出現。使用Javascript/JQuery提取兩個字符串模式之間的子字符串

例如:

如果文本是:

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus [[tag::4797897]] mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. 
[[tag::4797800]] [[tag::4797769]] 

正如我想[[標籤::],預期輸出應爲4797897之間的提取文本, 4797800和4797769

我正在使用Javascript和JQuery

Ca ñ一些請幫助我。在此先感謝

+1

你能顯示你的代碼嗎? – rapvelopment 2015-01-21 02:00:26

回答

1

爲了達到所期望的結果可以使用exec()方法在一個循環中,推capturing組的匹配結果的結果陣列。

var str = ' ... ' 
var re = /\[\[tag::([^\]]+)]]/g, 
matches = []; 

while (m = re.exec(str)) { 
    matches.push(m[1]); 
} 

console.log(matches) //=> [ '4797897', '4797800', '4797769' ] 
+0

完美的工作。非常感謝:) – user2975939 2015-01-21 02:38:30

+1

不客氣。下一次當這樣的問題被問到時,請考慮發佈您嘗試嘗試解決問題的內容。 – hwnd 2015-01-21 02:40:50

0

使用capturing groups

\[\[tag::(.*?)]] 

得到你想要從組索引1 .*?會做的零個或多個字符的非貪婪匹配的值。 [是一個正則表達式元字符,表示字符類的開始。因此,您需要在正則表達式中轉義[以匹配字面[符號。

DEMO

> var str = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus [[tag::4797897]] mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu.\nLorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus [[tag::4797897]] mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu.\n[[tag::4797800]] [[tag::4797769]]" 
> var re = /\[\[tag::(.*?)]]/g; 
> while (m = re.exec(str)) { 
... match.push(m[1]); 
... } 
> console.log(match) 
[ '4797897', '4797800', '4797769' ] 
相關問題