Python - Regex如何替换字符串中的字符?

时间:2013-08-10 19:30:54

标签: python regex replace

我已经尝试过re.search但是不知道正则表达式的确切语法要替换(两者之间的任何东西)。 假设有以下字符串:

D08838  Acotiamide hydrochloride hydrate (JAN/BBC); Acotiamide hydrochloride (USAN) Antagonist

我想得到这样的东西:

D08838  Acotiamide hydrochloride hydrate; Acotiamide hydrochloride  Antagonist

2 个答案:

答案 0 :(得分:0)

这个怎么样:

>>> import re
>>> s = "D08838  Acotiamide hydrochloride hydrate (JAN/BBC); Acotiamide hydrochloride (USAN) Antagonist"
>>> re.sub('\s\([\w/]+\)', '', s)
'D08838  Acotiamide hydrochloride hydrate; Acotiamide hydrochloride Antagonist'

答案 1 :(得分:0)

我会去:

import re
s = 'D08838  Acotiamide hydrochloride hydrate (JAN/BBC); Acotiamide hydrochloride (USAN) Antagonist'
print re.sub('(\s*\(.*?\))', '', s)
#D08838  Acotiamide hydrochloride hydrate; Acotiamide hydrochloride Antagonist