I'm trying to parse some mathematical expressions with re
(parenthesis content).
I've tried this :
>>> re.compile("\(.*\)").findall("(1 + 2) + (3 + 4)")
['(1 + 2) + (3 + 4)']
But I find only the biggest occurence, that include the content between the last and first parenthesis. But I would like to get only the smallest.
How could I achieve this?
>>> re.compile(<expr>).findall("(1 + 2) + (3 + 4)")
['(1 + 2)', '(3 + 4')]
I've tried to replace <expr>
with "\\((?![\\(\\)])+\\)"
(to exclude occurences with parenthesis within parenthesis) but it doesn't seem to work.
Instead of matching everything with .*
, exclude from that match the closing parentheses character:
>>> re.compile("\([^)]*\)").findall("(1 + 2) + (3 + 4)")
['(1 + 2)', '(3 + 4)']
See I am using
[^)]*
instead of
.*
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.