我试图用re (括号内容)解析一些数学表达式。
我试过这个:
>>> re.compile("\(.*\)").findall("(1 + 2) + (3 + 4)") ['(1 + 2) + (3 + 4)']但我发现的只是最大的事件,其中包括最后一个括号和第一个括号之间的内容。 但我想只得到最小的。
我怎么能实现这个目标?
>>> re.compile(<expr>).findall("(1 + 2) + (3 + 4)") ['(1 + 2)', '(3 + 4')]我试图将<expr>替换为"\((?![\(\)])+\)" (以在括号内用括号排除出现),但它似乎不起作用。
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.
最满意答案
不要将所有内容与.*匹配,而是从匹配的圆括号字符中排除:
>>> re.compile("\([^)]*\)").findall("(1 + 2) + (3 + 4)") ['(1 + 2)', '(3 + 4)']看我正在使用
[^)]*代替
.*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
.*更多推荐
发布评论