Charles Charles - 11 days ago 7
Python Question

Python re findall multiple occurrences allowing same characters

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?

sal sal
Answer

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?

Comments