像下面这样使用负前瞻。
>>> 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'更改内的数字
{}以替换字符串的第一个,第二个或第n个出现的字符串cat
要替换字符串的第三次出现
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'


