2

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?

0

1 Answer 1

3

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

r"\(([^()]*)\)"
Sign up to request clarification or add additional context in comments.

7 Comments

@WiktorStribiżew: "I want to process the inner (b) first before removing it and processing the outer parens" (emphasis mine). Once you replace the inner expression with a non-parenthesised expression, you can find the outer one. This would typically be done in a loop; no way to do it with one regexp execution.
This solves my issue Amadan. Thanks. Side question: what does "minimal" mean in python regex's if not "match as few characters as possible"?
Exactly that - but at the place where you're matching, For example, a.+z matched against abcz adz would match abcz adz - The first a available, then as much other characters as possible, then z. Only if the first a couldn't be worked into the match would the second a be tested, like with ad+z. In contrast, a.+?z will match abcz - the first a, as little other characters possible ("minimal"), then z. It will not match adz, because another viable match is available sooner.
Perhaps python docs should call it "earliest minimal" or "leftmost minimal" instead of just "minimal" then. I was quite misled by the term "minimal", thinking it meant "smallest possible"
Could you not just use "(\(.*?)(\(.*?\))(.*?\))" ? So that group(1) is the middle parameter, and concatenating group(0) and group(2) would get you the entire string without the middle section? Or am I not seeing the problem here?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.