如果包含字符串foo,请替换foo为bar.否则,追加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)
对于那些好奇的人,在我的应用程序中,我需要替换代码是由表驱动的 - 正则表达式和替换是从数据库中获取的.
这很棘手.在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)
尝试这个简单的单线程,没有正则表达式,没有技巧:
a.replace("foo", "bar") + (a.count("foo") == 0) * "bar"
Run Code Online (Sandbox Code Playgroud)