【问题标题】:How to replace a pattern in a string using the re module? [duplicate]如何使用 re 模块替换字符串中的模式? [复制]
【发布时间】:2020-12-28 20:25:26
【问题描述】:

Python (3.8.6) 模块 re 在字符串中找到给定的模式,但无法替换它。

# example text
x = """hello world
new line"""

re.search(r"^hello world$", x, re.MULTILINE) -> <re.Match object; span=(0, 11), match='hello world'>
# pattern found

re.sub(r"^hello world$", "SUB", x, re.MULTILINE) -> "hello world\nnew line"
# does not get replaced

谁能解释这种行为?

【问题讨论】:

    标签: python python-3.x regex python-re


    【解决方案1】:

    因为第三个参数是countflags 位于第 4 位。因此,请尝试:

    >>> re.sub(r"^hello world$", "SUB", x, flags=re.MULTILINE)
    'SUB\nnew line'
    

    请注意,您也可以编译模式并将标志放在那里:

    >>> p = re.compile(r"^hello world$", re.MULTILINE)
    ... re.sub(p, 'SUB', x)
    'SUB\nnew line'
    

    【讨论】:

    • 嗯,为什么投反对票?
    • 有人会认为你在这里花了足够的时间来停止关心......我也被否决了。
    • 哦,我不是特别在意,我只是好奇;如果答案没有帮助,我想知道原因。
    【解决方案2】:

    请参阅re.sub 的文档:

    $ pydoc3 re.sub
    Help on function sub in re:
    
    re.sub = sub(pattern, repl, string, count=0, flags=0)
        Return the string obtained by replacing the leftmost
        non-overlapping occurrences of the pattern in string by the
        replacement repl.  repl can be either a string or a callable;
        if a string, backslash escapes in it are processed.  If it is
        a callable, it's passed the Match object and must return
        a replacement string to be used.
    

    如您所见,flags 是最后一个以count 开头的参数 - 这个 是您分配给re.MULTILINE 的内容。使用:

    re.sub(r"^hello world$", "SUB", x, flags=re.MULTILINE)
    

    【讨论】:

      猜你喜欢
      • 2016-06-12
      • 1970-01-01
      • 2022-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多