Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
删除python中()和[]之间的文本,但有一些例外_Python_Regex - Fatal编程技术网

删除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]