Fixee
Fixee

Reputation: 1639

Finding shortest regex match in Python

I want to process a string like this (a (b) c) and I want to match the inner (b) first before processing the outer parens. However, this code doesn't work:

>>> x='(a(b)c)'
>>> re.search(r"\((.*?)\)", x).group(1)
'a(b'

Is there any way to ask Python to find a minimal match (ie, b) rather than the longer match a(b?

Upvotes: 2

Views: 346

Answers (1)

Amadan
Amadan

Reputation: 198324

XY problem. You can't process the minimal match. What you can do is find a match without parentheses.

r"\(([^()]*)\)"

Upvotes: 3

Related Questions