1

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())
4
  • You didn't think of using string concatenation? r'\b' + i + r'\b'? Commented Mar 8, 2018 at 0:40
  • You can search for all three at once: r'\b(text1|text2|text3)\b'. Have you tried that? Commented Mar 8, 2018 at 0:44
  • The list is likely to expand in the future to a decent size, so typing in all instances wouldn't be practical ( I'll update the original question to include the fact that the list is likely to grow) Commented Mar 8, 2018 at 0:50
  • @Barmar I tried this earlier but I guess something was wrong with my code because I just got it to work. Thanks for suggestion / answer Commented Mar 8, 2018 at 1:08

2 Answers 2

1

You can use the new f-strings.

for i in lst:
    my_regex =re.search(fr'\b{i}\b', sent)
    print(my_regex.group())
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

The regexp only matches whole words, this will match any substring.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.