删除python中()和[]之间的文本,但有一些例外

2024-04-25 17:44:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图过滤一些文本与不需要的字符之间的文本。下面是我要筛选的示例文本。你知道吗

*CHI:\t<that> [/] (.) that (i)s it . [+ bch]\n

尝试:

import re
s = '*CHI:\t<that> [/] (.) that (i)s it . [+ bch]\n'
s = re.sub('[()]','',s)
print(s)

我的输出是

*CHI:   <that> [/] . that is it . [+ bch]

我想保留(.),但要过滤I之间的括号,即将(I)改为I。同时我想保留[/]并删除[+bch]。如何过滤一个并保留另一个?你知道吗


Tags: 文本importre示例thatisit字符
2条回答

一种同时适用于两个Python版本的方法是

re.sub(r'\((?!\.\))|(?<!\(\.)\)', '', s)

参见regex demo

细节

  • \((?!\.\))-一种不紧跟在.)后面的(
  • |-或
  • (?<!\(\.)\)-a )前面不紧跟(.。你知道吗

作为替代方案,您可以在捕获组中添加异常作为替代方案,并替换为backreference(Python 3.5+)或lambda表达式(早期版本):

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]

参见Python 3.5 demothis Python 2.x demo。你知道吗

可以使用排除.的字符类:

s = re.sub(r'\(([^.])\)', r'\1', s)

有了这个变化,s将变成:

*CHI:   <that> [/] (.) that is it . [+ bch]

相关问题 更多 >