【发布时间】:2017-02-19 06:45:48
【问题描述】:
我正在尝试使用此正则表达式从字符串中删除方括号的所有实例(以及其中的所有内容)。例如,这在字符串中只有一对方括号时有效:
import re
pattern = r'\[[^()]*\]'
s = """Issachar is a rawboned[a] donkey lying down among the sheep pens."""
t = re.sub(pattern, '', s)
print t
我得到的是正确的:
>>>Issachar is a rawboned donkey lying down among the sheep pens.
但是,如果我的字符串包含一组以上的方括号,它就不起作用。例如:
s = """Issachar is a rawboned[a] donkey lying down among the sheep pens.[b]"""
我明白了:
>>>Issachar is a rawboned
无论字符串中有多少个方括号,我都需要正则表达式才能工作。正确答案应该是:
>>>Issachar is a rawboned donkey lying down among the sheep pens.
我研究并尝试了许多排列都无济于事。
【问题讨论】:
-
请注意,虽然正则表达式可以帮助您串联匹配括号(如 a[b]c[d]e),但它们通常无法处理所谓的nested parens problem。 (例如:a[b[c][d[e]]]。)不过,您可以通过专门编码一些最大嵌套数来“伪造”它。