A series of matches (non-nested) balanced parentheses at the end of a line

How can I match one or more expressions in brackets appearing at the end of a line?

Input:

'hello (i) (m:foo)'

Required Conclusion:

['i', 'm:foo']

Designed for python script. Paren markers cannot appear inside each other ( no nesting ), and brackets can be separated by spaces.

This is more complicated than it might seem at first glance, at least so it seems to me.

+3
source share
2 answers
paren_pattern = re.compile(r"\(([^()]*)\)(?=(?:\s*\([^()]*\))*\s*$)")

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

or even shorter:

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

explanations:

\(                     # 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
+7
source

You do not need to use regex:

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

. , . . MizardX, .

+5

Source: https://habr.com/ru/post/1703320/


All Articles