删除python中()和[]之间的文本,但有一些例外
我正在尝试过滤一些文本之间不需要的字符。下面是我要筛选的示例文本删除python中()和[]之间的文本,但有一些例外,python,regex,Python,Regex,我正在尝试过滤一些文本之间不需要的字符。下面是我要筛选的示例文本 *CHI:\t<that> [/] (.) that (i)s it . [+ bch]\n *CHI:\t[/](.)就是这样。[+bch]\n 尝试: import re s = '*CHI:\t<that> [/] (.) that (i)s it . [+ bch]\n' s = re.sub('[()]','',s) print(s) 重新导入 s='*CHI:\t[/](.)就是它。[+b
*CHI:\t<that> [/] (.) that (i)s it . [+ bch]\n
*CHI:\t[/](.)就是这样。[+bch]\n
尝试:
import re
s = '*CHI:\t<that> [/] (.) that (i)s it . [+ bch]\n'
s = re.sub('[()]','',s)
print(s)
重新导入
s='*CHI:\t[/](.)就是它。[+bch]\n'
s=re.sub('[()]','',s)
印刷品
我的输出是
*CHI: <that> [/] . that is it . [+ bch]
*CHI:[/]。就是这样。[+bch]
我想保留(.)但过滤I之间的括号,即将(I)更改为I。而我想保留[/]并删除[+bch]。如何过滤其中一个并保留另一个?您可以使用排除
的字符类:
s = re.sub(r'\(([^.])\)', r'\1', s)
通过此更改,s
将变为:
*CHI: <that> [/] (.) that is it . [+ bch]
*CHI:[/](.)就是这样。[+bch]
一种适用于两个Python版本的方法是
re.sub(r'\((?!\.\))|(?<!\(\.)\)', '', s)
请参阅和
import re
s = '*CHI:\t<that> [/] (.) that (i)s it . [+ bch]\n'
s = re.sub(r'(\(\.\))|[()]', r'\1', s)
# Python earlier than 3.5
# s = re.sub(r'(\(\.\))|[()]', lambda x: x.group(1) if x.group(1) else '', s)
print(s) # => *CHI: <that> [/] (.) that is it . [+ bch]