I have a list of strings and a list of regex patterns. What I want to achieve is that for every string in the list, I want to try matching the patterns found in the regex list that I have created. As soon as a match is found, I want to no longer look in the regex list for further matches.
Following is a simple version of my code:
str = ['catihavea', 'mycatisacatbigcat', 'mycatgetangrycatacat']
pattern = ['ttt$','cats$', 'cat$','at$']
lst=[]
for string in str:
for pat in pattern:
match = re.search(pat, string)
if match:
print(match.group())
lst.append(match.group())
break
else:
lst.append("None")
The output I’m getting is:
[‘None’, ‘None’, ‘cat’, ‘None’, ‘None’, ‘cat’, ‘None’, ‘None’, ‘cat’]
The output I want is:
[‘None’,‘cat’,‘cat’]
I want the new list ‘lst’ and the ‘str’ to be of the same length. That is why i want to append ‘None’ if no match is found.