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

标签 python regex

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

相关文章:

python - 将 Nmap 子进程中的数据直接存储到列表中

mysql 与正则表达式精确匹配?

javascript - 拆分 JS 字符串正则表达式大写后跟小写

python - SQLAlchemy 最新值的高效子查询

python - 为什么在使用 python 多处理池时会看到额外的换行符?

Python:如何阻止变量超过某个值?

python - Tornado 请求处理程序映射到国际字符

正则表达式问题 : independent position of words

regex - Perl 6中的递归正则表达式?

python dicttoxml 多次使用相同的键