我有一个像这样的文本文件-
{[a] abc (b(c)d)}
我想删除括号 [] 和 (())
之间的内容。所以输出应该是 -
abc
我删除了括号之间的内容但是无法删除此[]
之间的内容
我试过下面的代码 -
import re
with open('data.txt') as f:
input = f.read()
line = input.replace("{","")
line = line.replace("}","")
output = re.sub(r'\(.*\)', "", line)
print output
输出是-
[a] abc
在我的代码中,我首先替换了 {}
,然后从 ()
中删除了内容。我想在 output = re.sub(r'\(.*\)', "", line)
这一行添加 \[.*\]
。但找不到办法做到这一点。我还在学习python。所以我面临这个问题。请帮忙。
最佳答案
Imo 并不像乍看起来那么容易,您很可能需要一些平衡(递归)方法,这可以通过 newer regex
module 实现:
import regex as re
string = "some lorem ipsum {[a] abc (b(c)d)} some other lorem ipsum {defg}"
rx_part = re.compile(r'{(.*?)}')
rx_nested_parentheses = re.compile(r'\((?:[^()]*|(?R))*\)')
rx_nested_brackets = re.compile(r'\[(?:[^\[\]]*|(?R))*\]')
for match in rx_part.finditer(string):
part = rx_nested_brackets.sub('',
rx_nested_parentheses.sub('',
match.group(1))).strip()
print(part)
哪个会产生
abc
defg
模式是
\( # opening parenthesis
(?: # non.capturing group
[^()]* # not ( nor )
| # or
(?R) # repeat the pattern
)*
\)
关于python - 使用 python 正则表达式删除括号之间的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49915974/