[python]Modification of the regex code

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:
Screenshot 2019-08-21 at 11.59.08 AM
notice the spaces in between the string of each row will also be presented.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s