["python","regex"]
Python: How to use RegEx in an if statement?

I have the following code which looks through the files in one directory and copies files that contain a certain string into another directory, but I am trying to use Regular Expressions as the string could be upper and lowercase or a mix of both. Here is the code that works, before I tried to use RegEx's import os import re import shutil def test(): os.chdir("C:/Users/David/Desktop/Test/MyFiles") files = os.listdir(".") os.mkdir("C:/Users/David/Desktop/Test/MyFiles2") for x in (files): inputFile = open((x), "r") content = inputFile.read() inputFile.close() if ("Hello World" in content) shutil.copy(x, "C:/Users/David/Desktop/Test/MyFiles2") Here is my code when I have tried to use RegEx's import os import re import shutil def test2(): os.chdir("C:/Users/David/Desktop/Test/MyFiles") files = os.listdir(".") os.mkdir("C:/Users/David/Desktop/Test/MyFiles2") regex_txt = "facebook.com" for x in (files): inputFile = open((x), "r") content = inputFile.read() inputFile.close() regex = re.compile(regex_txt, re.IGNORECASE) Im guessing that I need a line of code that is something like if regex = re.compile(regex_txt, re.IGNORECASE) == True But I cant seem to get anything to work, if someone could point me in the right direction it would be appreciated.
import re if re.match(regex, content): blah.. You could also use re.search depending on how you want it to match. You can run this example: """ very nice interface to try regexes: https://regex101.com/ """ # %% """Simple if statement with a regex""" import re regex = r"\s*Proof.\s*" contents = ['Proof.\n', '\nProof.\n'] for content in contents: assert re.match(regex, content), f'Failed on {content=} with {regex=}' if re.match(regex, content): print(content)