Overlapping count of substring in a string in Python

后端 未结 8 2201
北恋
北恋 2021-01-07 03:42

I want to find all the counts (overlapping and non-overlapping) of a sub-string in a string. I found two answers one of which is using regex which is not my intention and t

8条回答
  •  清歌不尽
    2021-01-07 04:25

    A brute-force approach is just

    n = len(needle)
    count = sum(haystack[i:i+n] == needle for i in range(len(haystack)-n+1))
    

    (this works because in Python True and False are equivalent to numbers 1 and 0 for most uses, including math).

    Using a regexp instead it could be

    count = len(re.findall(needle[:1]+"(?="+re.escape(needle[1:])+")",
                           haystack))
    

    (i.e. using a(?=ba) instead of aba to find overlapping matches too)

提交回复
热议问题