如果没有x,则将x替换为y或附加y

geo*_*org 13 python regex

如果包含字符串foo,请替换foobar.否则,追加bar到字符串.如何用一个re.sub(或任何其他功能)调用来写这个?没有条件或其他逻辑.

import re

regex = "????"
repl  = "????" 

assert re.sub(regex, repl, "a foo b")       == "a bar b"
assert re.sub(regex, repl, "a foo b foo c") == "a bar b bar c"
assert re.sub(regex, repl, "afoob")         == "abarb"
assert re.sub(regex, repl, "spam ... ham")  == "spam ... hambar"
assert re.sub(regex, repl, "spam")          == "spambar"
assert re.sub(regex, repl, "")              == "bar"
Run Code Online (Sandbox Code Playgroud)

对于那些好奇的人,在我的应用程序中,我需要替换代码是由表驱动的 - 正则表达式和替换是从数据库中获取的.

Tim*_*ker 9

这很棘手.在Python中,替换文本反向引用未参与匹配的组是一个错误,因此我不得不使用先行断言构建一个非常复杂的构造,但它似乎通过了所有测试用例:

result = re.sub("""(?sx)
    (              # Either match and capture in group 1:
     ^             # A match beginning at the start of the string
     (?:(?!foo).)* # with all characters in the string unless foo intervenes
     $             # until the end of the string.
    |              # OR
     (?=foo)       # The empty string right before "foo"
    )              # End of capturing group 1
    (?:foo)?       # Match foo if it's there, but don't capture it.""", 
                     r"\1bar", subject)
Run Code Online (Sandbox Code Playgroud)


zen*_*poy 9

尝试这个简单的单线程,没有正则表达式,没有技巧:

a.replace("foo", "bar") + (a.count("foo") == 0) * "bar"
Run Code Online (Sandbox Code Playgroud)

  • 在我看来,这是唯一明智的解决方案; 在某些情况下,正则表达式不是最好的工具 - 这就是其中之一. (3认同)
  • 不幸的是,他似乎确实需要一个正则表达式(参见他的问题中的最后一句). (2认同)