如果字符串包含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"
对于那些好奇的人,在我的应用程序中,我需要替换代码是表驱动的——正则表达式和替换是从数据库中获取的。
最佳答案
这很棘手。在 Python 中,替换文本反向引用未参与比赛的组 are an error , 所以我不得不使用 lookahead assertions 构建一个相当复杂的结构,但它似乎通过了所有测试用例:
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)
关于python - 将 x 替换为 y,如果没有 x,则附加 y,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17274039/