This is a modification of the code I posted previously for regex practice.
I change the from split() to splitlines(), splitlines() will split which row of the string only when the end of string is detected hence will preserve the string that has whitespaces in between on each row.
import re from os.path import exists path = "path/of/your/file" pattern = "(foo\s*bar)" # change the pattern as necessary file = "your_filename" if exists(path + file): with open(path + file, "r") as file: rows = file.read() regex = re.compile(pattern) print([row for row in rows.splitlines() if regex.match(row)])
So here’s the example:
notice the spaces in between the string of each row will also be presented.