Python replace不会像I exp那样替换值

2024-04-19 09:40:17 发布

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

我有一个字符串,其中有一个子字符串,我想匹配和替换。你知道吗

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

我想删除x264-blblxcv。这条线没有按预期工作。你知道吗

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

Tags: 字符串titlereplacex264msdblblxcv
3条回答

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

使用^{} 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'

或者,在.x264-上用^{}分区:

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

^{}将不接受正则表达式作为输入。也许你想要^{}。你知道吗

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

如果要删除从“.x264”开始的部分,可以使用以下语句:

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

相关问题 更多 >