Capture any occurrence of word in a text; RegEx; Python
Question: I have a list of words that I want to cross-reference with a bunch of texts,
and if a word from the search string is present in the text, I want to retain
the text.

    
    
    search_string = ['Good', 'Bad', 'Ugly']
    

My code so far is:

    
    
    retained_texts = []
    for text in full_text:
        if set(text) & search_string:
            retained_texts.append(' '.join(text))
    

Here, `full_text` is a list of lists and `text` is a list of words.

This method has a very low level of accuracy, because it retains only texts
where the `Good`, the `Bad`, and the `Ugly` are separate words. However, it
rejects instances where they are imbedded in other words.

E.g.,

Instances like `Goodwill`, `Ugly-duckling`, `BadBoy`, `Good-Bad-Ugly` etc. are
all rejected, while I definitely need them to be retained.

I would assume this could be solved with regex, but my I frankly don't know
how.


Answer: You can do this with following regular expression:

    
    
    re.match('(Good|Bad|Ugly)', text)
    

So your full code would look something like this:

    
    
    import re
    
    search_string = ['Good', 'Bad', 'Ugly']
    pattern = '({0})'.format('|'.join(map(re.escape, search_string)))
    retained_texts = []
    for text in full_text:
        if re.search(pattern, text):
            retained_texts.append(' '.join(text))
    

**UPDATE:** As comments point out there is a problem if `search_string`
contains dots, parenthesis or any other characters that need to be escaped
within regular expressions. This can be fixed by calling `re.escape` when
pattern is being constructed, I've edited the example above accordingly.

