2013-06-25 87 views
2

我有一個大的字符串,我想從中提取圓括號內的所有部分。將大括號內的所有文本提取到字符串數組

說我有喜歡

一個字符串「這(一個)(一二)是(三級)」

我需要寫會返回一個數組的函數

["one", "one two", "three "] 

我試圖從這裏找到的一些建議寫一個正則表達式,並失敗,因爲我似乎只得到第一個元素,而不是一個正確的數組填充所有:http://jsfiddle.net/gfQzK/

var match = s.match(/\(([^)]+)\)/); 
alert(match[1]); 

有人能指出我在正確的方向?我的解決方案不必是正則表達式。

回答

3

你幾乎在那裏。你只需要改變一些東西。
首先,將全局屬性添加到您的正則表達式。現在您正則表達式應該是這樣的:

/\(([^)]+)\)/g 

然後,match.length將爲您提供匹配的數量。並提取匹配,使用索引如match[1]match[2]match[3] ...

4

您需要一個全局正則表達式。看看這有助於:

​​

match不會做,因爲它沒有捕捉全球正則表達式組。 replace可用於循環。

1

您需要使用全局標誌,如果你在那裏有新的線路多,不斷exec結果,直到你有數組中的所有結果:

var s='Russia ignored (demands) by the White House to intercept the N.S.A. leaker and return him to the United States, showing the two countries (still) have a (penchant) for that old rivalry from the Soviet era.'; 

var re = /\(([^)]+)\)/gm, arr = [], res = []; 
while ((arr = re.exec(s)) !== null) { 
    res.push(arr[1]);  
} 

alert(res); 

fiddle


供參考查閱mdn article on exec

相關問題