Charles Charles - 1 year ago 84
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 Source

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:

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?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download