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

2024-06-25 22:59:19 发布

您现在位置:Python中文网/ 问答频道 /正文

如果字符串包含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"

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


Tags: 函数字符串importrefoobarassert逻辑
3条回答

试试这个简单的一行代码,没有regexp,没有技巧:

a.replace("foo", "bar") + (a.count("foo") == 0) * "bar"

你能做到的

正则表达式:

^(?!.*foo)(.*)$|foo(\b)

或者

^{pr2}$

替换为:\1bar

作品here

这很棘手。在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)

相关问题 更多 >