【问题标题】:Python regex sub not working as expected when using alternatives in square brackets在方括号中使用替代项时,Python regex sub 无法按预期工作
【发布时间】:2019-12-30 20:07:06
【问题描述】:

我正在尝试使用 Python re 模块将字符串中的日期替换为 <Month Year>

我试过了:

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'

我哪里错了?

【问题讨论】:

  • [...] 是一个字符类。您的正则表达式正在寻找 JanuryApilMch| 中的字符。改为(?:...)

标签: regex python-3.x string replace


【解决方案1】:

括号表示其成员(字符)中的替代项,您需要括号。试试这个:

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'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多