仅使用 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'
^
断言我们在开始。(?:(?!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'
关于python - 如何使用 python 正则表达式查找和替换句子中第 n 次出现的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27589325/