繁体   English   中英

如何使用python正则表达式将String数据附加到某些位置?

[英]How do I append String data to certain positions using python regular expressions?

我正在研究一个简单的python脚本; 我有多个看起来像这样的字符串:

"Some show 14x01 - the one where they do thing 1"

"Some show 14x21 - the one where they do thing 2"

"Some show 10x11 - the one where they do thing 3"

我想替换和附加字符,以便将它们格式化为:

"Some show S14E01 - the one where they do thing 1"

"Some show S14E21 - the one where they do thing 2"

"Some show S10E11 - the one where they do thing 3"

因此,理想情况下,我要删除以大写字母E代替x并将S附加到String段的前面。

我已经找出用于识别要更改的部分的正则表达式,

r"\d{2}.\d{2}"

要么

r"\d{2}\w\d{2}"

并且已经猜到了这么多:

for file in files:
    strFileName = str(file)
    strFileName = re.sub(r"\d{2}.\d{2}", ) # Unsure here
    strNew_name = 'Some show - ' + str(file) # Unsure here
    os.rename(file, strNew_name)

但是,我对如何进行和完成此重命名过程不知所措。 有人可以帮助我找到答案还是将我引向已提出的SO问题,请您帮助我回答? 谢谢!

您可以在re.sub反向引用匹配的组

>>> import re
>>> s = "Some show 14x01 - the one where they do thing 1"
>>> re.sub(r"(\d{2}).(\d{2})", r"S\1E\2",s)
>>> 'Some show S14E01 - the one where they do thing 1'

这里\\1表示第一个匹配组, \\2表示第二个匹配组。

您可以创建一个函数以发送给sub

def replacement (match): return "S" + re.sub(r"[^\\d]", "E", match.group(0))

然后将其发送到sub

strFileName = re.sub(r"\\d{2}.\\d{2}", replacement, strFileName)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM