I need to find positions of all substrings matching a regular expression within a string. For instance, if the string is abbba and the regexp is (b|bb)(?=a), the result should be [(2, 4), (3, 4)].
What I’ve come up with is
def get_ranges(pattern: str, string: str) -> list[tuple[int, int]]:
n = len(string)
return [(start, end) for start in range(n + 1) for end in range(start, n + 1)
if re.fullmatch(f'.{{{start}}}({pattern}).{{{n - end}}}', string)]
But this tends to perform extremely slowly, especially given that it doesn’t allow precompiled regexps to be used. Are there any more efficient ways to solve the problem?