String count with overlapping occurrences

前端 未结 22 3540
耶瑟儿~
耶瑟儿~ 2020-11-21 23:25

What\'s the best way to count the number of occurrences of a given string, including overlap in Python? This is one way:

def function(string, str_to_search_f         


        
22条回答
  •  感动是毒
    2020-11-21 23:50

    How to find a pattern in another string with overlapping

    This function (another solution!) receive a pattern and a text. Returns a list with all the substring located in the and their positions.

    def occurrences(pattern, text):
        """
        input: search a pattern (regular expression) in a text
        returns: a list of substrings and their positions 
        """
        p = re.compile('(?=({0}))'.format(pattern))
        matches = re.finditer(p, text)
        return [(match.group(1), match.start()) for match in matches]
    
    print (occurrences('ana', 'banana'))
    print (occurrences('.ana', 'Banana-fana fo-fana'))
    

    [('ana', 1), ('ana', 3)]
    [('Bana', 0), ('nana', 2), ('fana', 7), ('fana', 15)]

提交回复
热议问题