0

So I want to filter a text for words with a user chosen suffix. Whenever I compile my pattern using a variable in it it doesn't work tho. The code below just returns nothing.

def regexFilter(inText, suffix):
    pattern = re.compile("r'\S*(?=" + suffix + ")\S*'")  
    outText = pattern.findall(inText)
    
    return outText

My current test input is this: "The regular expression looks_x for any words_x that starts with an upper case" and it should return "looks_x" and "words_x".

When I replaced the pattern with r'\S*(?=_x)\S*' it worked, but that doesn't really help as I need to have user input in the pattern.

  • 1
    `re.compile(r'\S*(?=' + re.escape(suffix) + r')\S*')` (though the lookahead is not necessary here, `re.compile(fr'\S*{re.escape(suffix)}\S*')` will work, too) – Wiktor Stribiżew Nov 09 '22 at 12:55

0 Answers0