仅使用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)
我上面有一个句子,其中“猫”一词在句子中出现了两次。我希望将第二次出现的“猫”更改为“公牛”,而第一个“猫”字不变。我的最后一句话如下:
“猫鹅老鼠马猪牛牛”。在我上面的代码中,我尝试了 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 https://regex101.com/r/sS1qO8/4
-
^
断言我们正处于起步阶段。
-
(?:(?!cat).)*
匹配任何字符,但不匹配cat
,零次或多次。
-
cat
匹配第一个cat
子串。
-
(?:(?!cat).)*
匹配任何字符,但不匹配cat
,零次或多次。
- 现在,将所有模式包含在捕获组中,例如
((?:(?!cat).)*cat(?:(?!cat).)*)
,以便我们稍后可以引用那些捕获的字符。
-
cat
现在接下来的第二个cat
字符串已匹配。
OR
>>> s = "cat goose mouse horse pig cat cow"
>>> re.sub(r'^(.*?(cat.*?){1})cat', r'\1Bull', s)
'cat goose mouse horse pig Bull cow'
更改里面的数字{}
替换字符串的第一次、第二次或第 n 次出现cat
替换第三次出现的字符串cat
, put 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'
在这里使用上面的正则表达式...... https://regex101.com/r/wP7pR2/52
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)