fork download
  1. import re
  2.  
  3. def count_overlapping(string, pattern):
  4. regex = '{}(?={})'.format(re.escape(pattern[:1]), re.escape(pattern[1:]))
  5. it = re.finditer(regex, string)
  6. # Consume iterator, get count with minimal memory usage
  7. return sum(1 for _ in it)
  8.  
  9. mystr = '^_^_^-_-'
  10. print(count_overlapping(mystr, '^_^'))
  11. print(count_overlapping(mystr, '-_-'))
  12. print(count_overlapping(mystr, ''))
  13. print(count_overlapping(mystr, 'x'))
Success #stdin #stdout 0.04s 9588KB
stdin
Standard input is empty
stdout
2
1
9
0