Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching for outermost parentheses using Python regex

Apologies for the ambiguous title, but I don't know how to word my problem in such a way that makes sense in a single sentence.

So I have some simple regex code to extract code between brackets.

^.*\((.*)\).*

This successfully works in Python with the following code.

m = re.search( "^.*\((.*)\).*" ,input)
if m:
    print(m.groups()[0])

My problem occurs when a closing bracket ) may be inside the outermost brackets. For example, my current code when given

nsfnje (19(33)22) sfssf

as an input would return

19(33

but I would like it to return.

19(33)22

I'm not sure how to fix this, so any help would be appreciated!

like image 495
Geesh_SO Avatar asked Feb 17 '23 21:02

Geesh_SO


1 Answers

>>> input = "nsfnje (19(33)22) sfssf"
>>> re.search( "\((.*)\)" ,input).group(1)
'19(33)22'

Note that this searches for outermost parentheses, even if they are unbalanced (e.g. "(1(2)))))"). It is not possible to search for balanced parentheses using a single standard regular expression. For more information, see this answer.

like image 124
NPE Avatar answered Feb 19 '23 11:02

NPE