Find the Words that Created by Removing Letters from Given String

I’m trying to write a code using regex and my text file. My file contains these words line by line:

each
expressions
flags
in
from
given
line
of
once
lines
no

My purpose is; displaying the words that created by removing letters from given substring.

For example; if my substring is "flamingoes", my output should be;

flags
in
line
lines
no

Because they are created from my substring by removing letters, and they are in my text file also.

I did many works about regex but I am interested about this challenge. Is there any regex solution for this?

Answer

You should create a regex for each word you are looking for. The expression .*? between each letter is a non-greedy pattern, which will avoid backtracking (at least some of it), and make the search faster.

For example, the regex for the word “given” would be g.*?i.*?v.*?e.*?n

import re

def hidden_words(needles, haystack):
    for needle in needles:
        regex = re.compile(('.*?').join(list(needle)))
        if regex.search(haystack):
            yield needle

needles = ['each', 'expressions', 'flags', 'in', 'from', 
           'given', 'line', 'of', 'once', 'lines', 'no']

print(*hidden_words(needles, 'flamingoes'), sep='n')