One solution is a custom findall()
function to that finds all occurrences of a string. It is a mix of the methods of the re.findall()
and the str.find()
method and returns a list indexes where all the matches start.
from typing import Optional
def findall(
pattern: str, string: str, start: Optional[int] = None, end: Optional[int] = None
):
"""Find all matches of a pattern in a string.
Arguments
---------
pattern : str
The string to find.
string : str
The string to search in.
start : int or None
Where in the string to start the search for matches.
end : int or None
Where in the string to end the search for matches.
Returns
-------
list
A list of of the index of the start of all matches.
If no matches are found the list is empty.
"""
i = string.find(pattern, start, end)
if i == -1:
return []
else:
return [i] + findall(pattern, string, i + 1, end)