2009-02-17 55 views
3

如何匹配出現在字符串末尾的一個或多個括號表達式?在字符串末尾匹配一系列(非嵌套)平衡圓括號

輸入:

'hello (i) (m:foo)' 

所需的輸出:

['i', 'm:foo'] 

旨在用於Python腳本。 Paren標記不能出現在彼此的內部(no nesting),並且括號內的表達式可能被空格分隔。

看起來比乍看起來要困難,至少在我看來似乎如此。

回答

7
paren_pattern = re.compile(r"\(([^()]*)\)(?=(?:\s*\([^()]*\))*\s*$)") 

def getParens(s): 
    return paren_pattern.findall(s) 

甚至更​​短:

getParens = re.compile(r"\(([^()]*)\)(?=(?:\s*\([^()]*\))*\s*$)").findall 

交代:

\(     # opening paren 
([^()]*)    # content, captured into group 1 
\)      # closing paren 
(?=     # look ahead for... 
    (?:\s*\([^()]*\))* # a series of parens, separated by whitespace 
    \s*     # possibly more whitespace after 
    $     # end of string 
)      # end of look ahead 
5

你不需要使用正則表達式:

def splitter(input): 
    return [ s.rstrip(" \t)") for s in input.split("(") ][1:] 
print splitter('hello (i) (m:foo)') 

注:如果輸入已經知道是有效的這種解決方案僅適用。請參閱MizardX的解決方案,該解決方案可用於任何輸入。

+0

該規範是,我們只在字符串的結尾匹配括號表達式。給定的實現不起作用,如果我們有括號的表達式*,而不是在我們想避免匹配的字符串的末尾。 – 2009-02-17 02:47:06