+-
如何使用python正则表达式查找和替换句子中第n个单词的出现?
仅使用 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)

我上面有一句话,“cat”这个词出现在句子中两次.我希望第二次出现的’猫’改为’公牛’,留下第一个’猫’字.我的最后一句话看起来像:
“猫鹅鼠马猪公牛”.在我上面的代码中,我试过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正则表达式查找和替换句子中第n个单词的出现? - 乐贴网