Python 正则表达式替换所有模式,除非它位于重复模式旁边

标签 python regex

我正在使用 Python,并且有一个多行字符串,如下所示:

The quick brown fox jumps over the lazy dog. 
The quick quick brown fox jumps over the quick lazy dog. This a very very very very long line.
This line has other text?
The quick quick brown fox jumps over the quick lazy dog.

我想用 slow 替换所有出现的 quick,但有一个异常(exception)。当 quick 后面接着 quick 时,只有第一个 quick 会被第二个 quick 转换,相邻的 quick 保持不变.

因此,输出应如下所示:

The slow brown fox jumps over the lazy dog. 
The slow quick brown fox jumps over the slow lazy dog. This a very very very very long line.
This line has other text?
The slow quick brown fox jumps over the slow lazy dog.

我可以使用多次传递来完成此操作,首先将所有内容转换为慢速,然后在第二次传递期间转换边缘情况。但我希望有一个更优雅或更明显的一次性解决方案。

最佳答案

这是不支持前瞻的正则表达式引擎的变体:

quick(( quick)*)

替换为

slow\1

关于Python 正则表达式替换所有模式,除非它位于重复模式旁边,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56939340/

相关文章:

python - Xgboost plot_tree 错误 : ValueError: booster must be Booster instance

c# - 为什么我的 C# 代码中出现 "The name Regex does not exist in the current context"?

c# - 匹配负序

能记住算术运算的类似 Python 数字的类?

python - 如何在 Python 中动态移动嵌套字典

使用 API 获取 json 中的 xml 数据的 python 脚本

python - 在没有 nohup + ps aux grep + kill 的情况下启动/停止后台 Python 进程

regex - Emacs:如何复制正则表达式匹配?

正则表达式匹配以单词开头并以或不以数字结尾的字符串

javascript - 具有非全局正则表达式的 `match` 和 `exec` 似乎两次返回第一个匹配项