【问题标题】:re.DOTALL works for re.match but not re.sub? [duplicate]re.DOTALL 适用于 re.match 但不适用于 re.sub? [复制]
【发布时间】:2017-01-27 07:08:31
【问题描述】:

为什么这个匹配如预期,但未能 sub?单行 s 工作正常。

import re
s = """<script>
wut</script>"""
print(re.match('<script(.*?)</script>', s, re.DOTALL).groups())
# Returns ('>\nwut',)
print(re.sub('<script(.*?)</script>', '', s, re.DOTALL))
# Returns <script>
# wut</script>

我只是想明白这一点;无需建议 Beautiful Soup 或手动解析。

【问题讨论】:

    标签: python regex


    【解决方案1】:

    re.sub 的 4h 参数是计数而不是标志,您可以使用:

    >>> print re.sub('<script.*?</script>', '', s, 0, re.DOTALL)
    ''
    

    这里我们传递count=0,这意味着任何# 个替换。

    Signature of re.sub is:

    re.sub(pattern, repl, string, count=0, flags=0)
    

    【讨论】:

    • 这可以节省我一个小时
    猜你喜欢
    • 1970-01-01
    • 2018-03-14
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 2013-05-14
    • 2014-09-28
    • 1970-01-01
    相关资源
    最近更新 更多