Match at every second occurrence

Use capturing groups.

foo.*?(foo)

Use a regex like this to match all occurrences in a string. Every returned match will contain a second occurrence as its first captured group.

Here’s an example that matches every second occurrence of \d+ in Python using findall:

import re

input="10 is less than 20, 5 is less than 10"
second_occurrences = re.findall(r'\d+.*?(\d+)', input)

print(second_occurrences)

Output:

['20', '10']

Leave a Comment