vkp vkp - 1 year ago 59
Python Question

Can number of matches in a regex be looped over?

I have the following

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

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

Is it possible to loop through the regex (changing
in the above regex to be
) 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 Source

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

import re

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


This will print out:

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