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

标签 python regex python-3.x replace

我正在编写一个简单的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 附加到字符串段的前面。

我已经找到了用于标识要更改的部分的正则表达式,

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)

但我不知道如何继续和完成这个重命名过程。有人可以帮助指导我找到答案或指导我找到一个已提出的问题来帮助我回答吗?谢谢!

最佳答案

您可以反向引用 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 指的是第二个匹配组。

关于python - 如何使用 python 正则表达式将字符串数据附加到某些位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49216652/

相关文章:

java - String.matches() 意外返回 false。

python - 尝试让 python RegEx 删除括号 [ abc ] 之间的所有内容

java - 正则表达式分隔带异常的表达式列表

python - 使用python3查找表情符号的宽度

python - Python 中内部函数的重用

python - 防止 Numpy 生成 NaN

python - python中的运算符重载

python - `cat` 在 ipython 交互式 shell 中如何工作?

python - pip 安装失败,出现 : OSError: [Errno 13] Permission denied on directory

python - 即使答案错误,Python 的分数也会增加