0
import re
print(len(re.findall('ANA', 'BANANA')))

This outputs 1, but I want to count matches using characters inclusively, so the output should be 2. Can this be done using re findall?

Char
  • 1,635
  • 7
  • 27
  • 38
  • no, you'll have to write code to change the anchor point iteratively. What you want are overlapping matches, but the methods of the `re` module only find non-overlapping matches. – President James K. Polk Nov 23 '16 at 01:13

1 Answers1

2

You cannot do that with the currently standard re module. However, as pointed out in other threads, you could use the newer regex module which offers an overlapped flag:

import regex
print(len(regex.findall('ANA', 'BANANA', overlapped=True)))

Information on regex module can be found here: https://pypi.python.org/pypi/regex

You will likely have to install it as:

pip install regex

The other threads mentioned: How to find overlapping matches with a regexp? and Python regex find all overlapping matches?

Community
  • 1
  • 1
sal
  • 3,515
  • 1
  • 10
  • 21