Find a string

  • + 1 comment

    While Python doesn't provide a way to count number of overlapping occurance, we can use regex to that with lookahead.

    The concept it to iter over all elements and check if ahead of every chsrector is our sub_string. Since we are using lookahead the pointor or cursor doesn't move for checking hence next element will not be after the match rather just next index item.

    For this regex is: f'(?={sub_string})' where f is to make this fromated string and replce {substring} with sub_string.

    def count_substring(string, sub_string):
        
        return len([m.start() for m in re.finditer(f'(?={sub_string})', string)])