Is there a way to specify a regular expression to match every 2nd occurrence of a pattern in a string?
Examples
- searching for a against string abcdabcd should find one occurrence at position 5
- searching for ab against string abcdabcd should find one occurrence at position 5
- searching for dab against string abcdabcd should find no occurrences
- searching for a against string aaaa should find two occurrences at positions 2 and 4
Use capturing groups.
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 usingfindall:Output: