【问题标题】:How do I append String data to certain positions using python regular expressions?如何使用 python 正则表达式将字符串数据附加到某些位置?
【发布时间】:2018-03-11 04:32:29
【问题描述】:

我正在编写一个简单的 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)

但是我不知道如何进行和完成这个重命名过程。有人可以帮助指导我找到答案或将我引导到一个已被问到的 SO 问题,这将帮助我回答它吗?谢谢!

【问题讨论】:

  • 我建议将其更改为 \d{1,2} 以防出现 2x5 而不是 02x05。

标签: python regex python-3.x replace


【解决方案1】:

您可以在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指第二个匹配组。

【讨论】:

    【解决方案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)

    【讨论】:

      猜你喜欢
      • 2020-02-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-06
      • 1970-01-01
      • 2023-02-03
      • 2013-06-29
      • 2011-08-13
      相关资源
      最近更新 更多