正则表达式:用另一种模式替换一种模式 [英] Regex: Replace one pattern with another

查看:57
本文介绍了正则表达式:用另一种模式替换一种模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用另一种正则表达式模式替换一个正则表达式模式.

I am trying to replace one regex pattern with another regex pattern.

st_srt = 'Awake.01x02.iNTERNAL.WEBRiP.XViD-GeT.srt'
st_mkv = 'Awake.S01E02.iNTERNAL.WEBRiP.XViD-GeT.mkv'

pattern = re.compile('\d+x\d+') # for st_srt
re.sub(pattern, 'S\1E\2',st_srt)

我知道这里使用 S\1E\2 是错误的.使用 \1 和 \2 的原因是为了捕获值 01 和 02 并在 S\1E\2 中使用它.

I know the use of S\1E\2 is wrong here. The reason am using \1 and \2 is to catch the value 01 and 02 and use it in S\1E\2.

我想要的输出是:

st_srt = 'Awake.S01E02.iNTERNAL.WEBRiP.XViD-GeT.srt'

那么,实现这一目标的正确方法是什么.

So, what is the correct way to achieve this.

推荐答案

您需要捕捉您想要保留的内容.试试这个:

You need to capture what you're trying to preserve. Try this:

pattern = re.compile(r'(\d+)x(\d+)') # for st_srt
st_srt = re.sub(pattern, r'S\1E\2', st_srt)

这篇关于正则表达式:用另一种模式替换一种模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆