vkp vkp - 2 years ago 91
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']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download