python - 如何使用 python 正则表达式查找和替换句子中第 n 次出现的单词?

标签 python regex

仅使用 python 正则表达式,如何查找和替换句子中第 n 次出现的单词? 例如:

str = 'cat goose  mouse horse pig cat cow'
new_str = re.sub(r'cat', r'Bull', str)
new_str = re.sub(r'cat', r'Bull', str, 1)
new_str = re.sub(r'cat', r'Bull', str, 2)

我上面有一个句子,其中“猫”这个词在句子中出现了两次。我想将第二次出现的“猫”更改为“公牛”,而第一个“猫”字保持不变。我的最后一句话看起来像: “猫鹅鼠马 pig 牛牛”。在我上面的代码中,我尝试了 3 次不同的时间无法得到我想要的。

最佳答案

像下面这样使用负前瞻。

>>> s = "cat goose  mouse horse pig cat cow"
>>> re.sub(r'^((?:(?!cat).)*cat(?:(?!cat).)*)cat', r'\1Bull', s)
'cat goose  mouse horse pig Bull cow'

DEMO

  • ^ 断言我们在开始。
  • (?:(?!cat).)* 匹配任何字符但不属于 cat ,零次或多次。
  • cat 匹配第一个 cat 子串。
  • (?:(?!cat).)* 匹配任何字符但不属于 cat ,零次或多次。
  • 现在,将所有模式包含在一个捕获组中,如 ((?:(?!cat).)*cat(?:(?!cat).)*),以便我们稍后可以引用那些捕获的字符。
  • cat 现在匹配下面的第二个 cat 字符串。

>>> s = "cat goose  mouse horse pig cat cow"
>>> re.sub(r'^(.*?(cat.*?){1})cat', r'\1Bull', s)
'cat goose  mouse horse pig Bull cow'

更改 {} 中的数字以替换字符串 cat 的第一次、第二次或第 n 次出现

要替换字符串 cat 的第三次出现,请将 2 放在花括号中..

>>> re.sub(r'^(.*?(cat.*?){2})cat', r'\1Bull', "cat goose  mouse horse pig cat foo cat cow")
'cat goose  mouse horse pig cat foo Bull cow'

Play with the above regex on here ...

关于python - 如何使用 python 正则表达式查找和替换句子中第 n 次出现的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27589325/

相关文章:

javascript - Selenium:如何在Python中使用selenium在内部div中滚动

python - 我可以在 GAE 上使用 django.contrib.gis 吗?

python - 删除未闭合的括号

regex - 如何用 Perl 正则表达式替换重叠匹配项?

regex - 如何在 Rust 中获取重叠的正则表达式捕获?

python - 使 Python 脚本可执行 chmod755?

python - 线程在调用 Thread.start 之前开始运行

c# - Uri.UnescapeDataString 在不同的计算机上失败

php正则表达式检查一个数字是否由5位数字组成

python - 使用 python 的朴素贝叶斯分类器