如果字符串包含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"
对于那些好奇的人,在我的应用程序中,我需要替换代码是表驱动的-正则表达式和替换是从数据库中获取的。在
试试这个简单的一行代码,没有regexp,没有技巧:
你能做到的
正则表达式:
或者
^{pr2}$替换为:
\1bar
作品here
这很棘手。在Python中,替换文本反向引用未参与匹配are an error的组,因此我不得不使用lookahead assertions构建一个相当复杂的构造,但它似乎通过了所有的测试用例:
相关问题 更多 >
编程相关推荐