Skip to content
Advertisement

Merge the matches from regular expressions into a single list

I am trying to separate a string in CamelCase into a single list

I managed to separate the words with regular expressions

But I am clueless on how create a single list of all the matches

I tried to concatenate the lists, append something like that but I don’t think it would work in my case

n="SafaNeelHelloAByeSafaJasleen"
patt=re.compile(r'([A-Z][a-z]*|[a-z$])')
matches=patt.finditer(n)
for match in matches:
    a=match.group()
    list=a.split()
    print(list)

output:

['Safa']

['Neel']

['Hello']

['A']

['Bye']

['Safa']

['Jasleen']

Desired output:

['Safa','Neel','Hello','A','Bye','Safa','Jasleen']

Advertisement

Answer

You’re looking for re.findall(), not re.finditer():

>>> string = "SafaNeelHelloAByeSafaJasleen"
>>> pattern = re.compile(r"([A-Z][a-z]*|[a-z$])")
>>> pattern.findall(string)
['Safa', 'Neel', 'Hello', 'A', 'Bye', 'Safa', 'Jasleen']
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement