代码之家  ›  专栏  ›  技术社区  ›  Superdooperhero

在方括号中使用替代项时,Python regex sub无法按预期工作

  •  -1
  • Superdooperhero  · 技术社区  · 5 年前

    我试图用字符串替换日期 <Month Year> 使用Python re 模块。

    我试过:

    import re
    s = "Wikipedia articles containing buzzwords from April 2014\t23"
    s = re.sub(r"[January|April|March]\s+\d{1,4}", "<Month Year>", s)
    

    但是它返回:

    'Wikipedia articles containing buzzwords from Apri<Month Year>\t23'
    

    而不是我所期望的:

    'Wikipedia articles containing buzzwords from <Month Year>\t23'
    

    我哪里做错了?

    1 回复  |  直到 5 年前
        1
  •  1
  •   SCouto    5 年前

    括号是指在其成员(字符)中需要括号的替代项。试试这个:

    s = re.sub(r"(January|April|March)\s+\d{1,4}", "<Month Year>", s)
    

    快速示例:

    >>> import re
    >>> s = "Wikipedia articles containing buzzwords from April 2014\t23"
    >>> s = re.sub(r"(January|April|March)\s+\d{1,4}", "<Month Year>", s)
    >>> s
    'Wikipedia articles containing buzzwords from <Month Year>\t23'