vkp vkp - 7 months ago 9
Python Question

Can number of matches in a regex be looped over?

I have the following

regex
to find matches in a string that are 3 character matches for a pattern.

import re
s="banana"
print re.findall(r'(?=([^aeiou].{2}))',s,re.I)


Is it possible to loop through the regex (changing
{2}
in the above regex to be
{0},{1},{3},{4},{5}
) so i get all the character matches <= length of the string?

In this case i would like to get all the 1,2,3,4,5,6 character matches that don't start with a vowel.

The result would be

['b', 'n', 'n','ba','na','na','ban','nan','bana','nana','banan','banana']

Answer

You can simply loop over the numbers in a for loop and format in the desired number with %d.

import re
s="banana"

result = []
for i in range(len(s)):
    part = re.findall(r'(?=([^aeiou].{%d}))'%i, s,re.I)
    result.extend(part)

print(result)

This will print out:

['b', 'n', 'n', 'ba', 'na', 'na', 'ban', 'nan', 'bana', 'nana', 'banan', 'banana']