【问题标题】:Python re.sub with a flag does not replace all occurrences带有标志的 Python re.sub 不会替换所有出现
【发布时间】:2010-09-07 17:46:11
【问题描述】:

Python 文档说:

re.MULTILINE:指定时,模式字符 '^' 匹配字符串的开头和每行的开头(紧跟在每个换行符之后)... 默认情况下,'^' 仅匹配开头字符串...

那么当我得到以下意外结果时是怎么回事?

>>> import re
>>> s = """// The quick brown fox.
... // Jumped over the lazy dog."""
>>> re.sub('^//', '', s, re.MULTILINE)
' The quick brown fox.\n// Jumped over the lazy dog.'

【问题讨论】:

    标签: python regex


    【解决方案1】:

    re.sub的定义:

    re.sub(pattern, repl, string[, count, flags])
    

    第 4 个参数是计数,您使用 re.MULTILINE(即 8)作为计数,而不是作为标志。

    要么使用命名参数:

    re.sub('^//', '', s, flags=re.MULTILINE)
    

    或者先编译正则表达式:

    re.sub(re.compile('^//', re.MULTILINE), '', s)
    

    【讨论】:

    • 最好有re.compile('^//', re.M).sub('', s)
    • 如果你告诉python你正在传递它的标志,你不必编译它
    • @pseudosudo flags 参数是在 Python 2.7 中添加的,在发布此答案时该参数不存在。我已将信息添加到答案中。
    【解决方案2】:
    re.sub('(?m)^//', '', s)
    

    【讨论】:

    • @MJM 在这种情况下,您不需要函数参数中的MULTILINE 标志。它已经具有多行的内联标志:(?m)
    • 不错的@mypetlion - gotya (y)
    【解决方案3】:

    re.sub的完整定义是:

    re.sub(pattern, repl, string[, count, flags])
    

    这意味着如果你告诉Python参数是什么,那么你可以传递flags而不传递count

    re.sub('^//', '', s, flags=re.MULTILINE)
    

    或者,更简洁:

    re.sub('^//', '', s, flags=re.M)
    

    【讨论】:

    • @agf 啊,我没想到看日期。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-08
    • 1970-01-01
    • 2018-05-15
    • 2012-11-24
    相关资源
    最近更新 更多