2013-12-08 95 views
0

假設我有一個包含字符串子Python的正則表達式:匹配嵌套括號

# the substrings and the whole string surrounded by parenthesis 
string = '((substring1)(substring2))' 


我想用正則表達式來同時獲得substring1 & substring2,但我有一個問題:(

這是我現在有:

match = re.search('(\(.*\))', string) 
print match.groups() 


的問題是,結果表明:

('(substring1)(substring2)',) 


好像正則表達式匹配只有第一個左括號和最後一個右括號..

換句話說,匹配正則表達式是如..

( match..... ) 

代替的

( (match1)(match2) ) 

我該怎麼做rege x捕獲INNER圓括號?

感謝

回答

6
>>> re.findall('\([^()]*\)', string) 
['(substring1)', '(substring2)'] 

要注意,正則表達式不能處理嵌套的任意水平是非常重要的。這將會找到最深層嵌套的項目,但如果你想找更復雜的東西,最好放棄正則表達式。

+0

OP問了一個類似的問題http://stackoverflow.com/questions/20449800/python-regex-nested-parenthesis – thefourtheye