Python:如何将嵌套括号与正则表达式匹配? [英] Python: How to match nested parentheses with regex?

查看:349
本文介绍了Python:如何将嵌套括号与正则表达式匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试匹配带有嵌套括号的类似数学表达式的字符串.

import re

p = re.compile('\(.+\)')
str = '(((1+0)+1)+1)'
print p.findall(s)

['((((1 + 0)+1)+1)']

我希望它匹配所有包含的表达式,例如(1 + 0),((1 + 0)+1)...
我什至不在乎它是否与诸如(((1 + 0),

为什么还没有这样做,我该怎么办?

解决方案

正则表达式尝试匹配尽可能多的文本,从而消耗了所有字符串.它不会在该字符串的某些部分上寻找正则表达式的其他匹配项.这就是为什么您只能得到一个答案的原因.

解决方案是不使用正则表达式.如果您实际上是试图解析数学表达式,请使用真实的解析解决方案.如果您真的只想捕获括号中的片段,则只需在看到(和)时循环计数字符,然后增加一个递减的计数器即可.

I'm trying to match a mathematical-expression-like string, that have nested parentheses.

import re

p = re.compile('\(.+\)')
str = '(((1+0)+1)+1)'
print p.findall(s)

['(((1+0)+1)+1)']

I wanted it to match all the enclosed expressions, such as (1+0), ((1+0)+1)...
I don't even care if it matches unwanted ones like (((1+0), I can take care of those.

Why it's not doing that already, and how can I do it?

解决方案

The regular expression tries to match as much of the text as possible, thereby consuming all of your string. It doesn't look for additional matches of the regular expression on parts of that string. That's why you only get one answer.

The solution is to not use regular expressions. If you are actually trying to parse math expressions, use a real parsing solutions. If you really just want to capture the pieces within parenthesis, just loop over the characters counting when you see ( and ) and increment a decrement a counter.

这篇关于Python:如何将嵌套括号与正则表达式匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆