J_Win
J_Win

Reputation: 97

Is it possible to create a REGEX loop that iterates through a list

I'm using the following to find whether a text exist in the sentence and printing out that text:

Example:

import re

lst = ['text1','text2','text3']

sent = 'This is a test to find text1 and text3'

my_regex =re.search(r'\b(text1)\b', sent)

print(my_regex.group())

text1

Question:

is it possible to create a loop similar to the following that will iterate and update the re.search with each value in the list:

note - The list is likely to expand beyond the three listed in the example

for i in lst:
    my_regex =re.search(r'\b(i)\b', sent)
    print(my_regex.group())

Upvotes: 1

Views: 56

Answers (2)

Srdjan M.
Srdjan M.

Reputation: 3405

[item for item in lst if re.search(r'\b%s\b' % item, sent)]

Or you can use faster solution (~38 times):

[s for s in sent.split() if s in lst]

Output:

['text1', 'text3']

Upvotes: 0

mypetlion
mypetlion

Reputation: 2524

You can use the new f-strings.

for i in lst:
    my_regex =re.search(fr'\b{i}\b', sent)
    print(my_regex.group())

Upvotes: 1

Related Questions