Python Regex: To Capture All Words Within Nested Parentheses
I am trying to extract all words within nested parentheses by using regex. Here is an example of my .txt file: hello (( (alpha123_4rf) 45beta_Frank)) Red5Great_Sam_Fun I have tri
Solution 1:
If the parantheses are directly following each other, this simpler solution would also do it:
def find_brackets(text):
rx = "(?s)\(\((.+)\)\)"
z = re.search(rx,text)
if z:
return z[0]
else:
return ''
Solution 2:
Try this pattern (?s)\([^(]*\((.+)\)[^)]*\)
Explanation:
(?s)
- flag: single line mode - .
matches also newline character
\(
- match (
literally
[^(]*
- match zero or more characters other from (
\(
- match (
literally
(.+)
- match one or mroe of any characters and store it inside first capturing group
\)
- match )
literally
[^)]*
- match zero or more characters other from )
\)
- match )
literally
Post a Comment for "Python Regex: To Capture All Words Within Nested Parentheses"