How can I find the number of overlapping sequences in a String with Python? [duplicate]

As an alternative to writing your own search function, you could use the re module:

In [22]: import re

In [23]: haystack = 'abababa baba alibababa'

In [24]: needle="baba"

In [25]: matches = re.finditer(r'(?=(%s))' % re.escape(needle), haystack)

In [26]: print [m.start(1) for m in matches]
[1, 3, 8, 16, 18]

The above prints out the starting positions of all (potentially overlapping) matches.

If all you need is the count, the following should do the trick:

In [27]: len(re.findall(r'(?=(%s))' % re.escape(needle), haystack))
Out[27]: 5

Leave a Comment