[python]Regex search and replace

This is a code snippet to do search and replace

import re
from os.path import exists

# change the path of the file you want to match
path = "/your/file/path/"
pattern = "\(([0-9]{3})\)(\.[0-9]{3}\.[0-9]{4})" # change regex as appropriate
file = "regex30.txt" # change the filename as appropriate
replace_pattern = r"\1\2" # change replace pattern as appropriate

if exists(path + file):
    with open(path + file, "r") as file:
        rows = file.read()
    for row in rows.splitlines():
        print("Before replace is {}".format(row))
        print("After replace is {}\n".format(re.sub(pattern, replace_pattern, row)))

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