Python替换不会像我期望的那样替换值

时间:2014-01-26 08:45:23

标签: python regex replace

我有一个字符串,它有一个我想匹配和替换的子字符串。

movie.2002.german.720p.x264-msd...

我想删除x264-blblxcv。此行无法按预期工作。

title = title.replace('.x264-\S+','')

3 个答案:

答案 0 :(得分:8)

str.replace() 支持正则表达式。您只能使用该方法替换文字文本,并且输入字符串不包含文字文本.x264-\S+

使用re.sub() method执行您想要的操作:

import re

title = re.sub(r'\.x264-\S+', '', title)

演示:

>>> import re
>>> title = 'movie.2002.german.720p.x264-msd...'
>>> re.sub(r'\.x264-\S+', '', title)
'movie.2002.german.720p'

或者,使用str.partition()分区.x264-

title = title.partition('.x264-')[0]

答案 1 :(得分:2)

str.replace不接受正则表达式作为输入。也许你想要re.sub

import re
title, pattern = "movie.2002.german.720p.x264-msd...", re.compile("\.x264-\S+")
print pattern.sub('', title) # or re.sub(pattern, '', title)

<强>输出

movie.2002.german.720p

答案 2 :(得分:1)

如果要从'.x264'开始删除部件,可以使用如下语句:

title=title[:title.find('.x264')]