Home > Mobile >  Merge the matches from regular expressions into a single list
Merge the matches from regular expressions into a single list

Time:06-28

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']

CodePudding user response:

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']

CodePudding user response:

You can append the matches to new list:

new_list=[]
for match in matches:
    a=match.group()
    new_list.append(a)

Output of new_list:

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