代码之家  ›  专栏  ›  技术社区  ›  James Holland

带数字的python正则表达式问题

  •  0
  • James Holland  · 技术社区  · 7 年前

    我需要在一组文件名中找到3或4位后的空格,并用下划线替换。但我似乎连4位数都找不到。

    s = "the blue dog and blue cat wore blue hats"
    p = re.compile(r'blue (?P<animal>dog|cat)')
    print(p.sub(r'gray \g<animal>',s))
    
    #Gives basically what I want.
    the gray dog and gray cat wore blue hats
    
    
    s = "7053 MyFile.pptx"
    p = re.compile('[0-9][0-9][0-9][0-9](?P<dig> )')
    print(p.sub('_\g<dig>', s))
    
    #Takes out the numbers, which I need to keep
    _ MyFile.pptx
    

    我做的每件事都有一个表达式,去掉了我需要保留的数字。

    最后,我想

    7035我的文件.pptx

    成为

    7035诳myfile.pptx

    1 回复  |  直到 7 年前
        1
  •  3
  •   Ondrej K.    7 年前

    如果您要将3或4位数字替换为空白,后面跟一个数字,后面跟一个下划线,正确的regex语法/替换将是:

    re.sub(r"([0-9]{3,4})\s", r"\1_", s)
    

    您可能误解了组/反向引用的工作原理。应该在组中的内容,需要在括号内。如果要使用命名组(这有点不必要):

    re.sub(r"(?P<dig>[0-9]{3,4})\s", r"\g<dig>_", s)
    

    或者使用类似于示例的预编译regex:

    s = "7053 MyFile.pptx"
    p = re.compile(r"(?P<dig>[0-9]{3,4})\s")
    print(p.sub('\g<dig>_', s))
    

    {3,4} 下列的 [0-9] 意思是三到四场比赛。 \s 代表空白(不仅仅是空白)。

    实际上,只要查找3位数字就可以匹配4位数字,因为我们不限制匹配模式之前发生的事情。根据您要查找的内容,您可能希望通过在模式前面加上 ^ (行首)或 \b 单词边缘有空字符…