Python string.replace regular expression [duplicate] Python string.replace regular expression [duplicate] python python

Python string.replace regular expression [duplicate]


str.replace() v2|v3 does not recognize regular expressions.

To perform a substitution using a regular expression, use re.sub() v2|v3.

For example:

import reline = re.sub(           r"(?i)^.*interfaceOpDataFile.*$",            "interfaceOpDataFile %s" % fileIn,            line       )

In a loop, it would be better to compile the regular expression first:

import reregex = re.compile(r"^.*interfaceOpDataFile.*$", re.IGNORECASE)for line in some_file:    line = regex.sub("interfaceOpDataFile %s" % fileIn, line)    # do something with the updated line


You are looking for the re.sub function.

import res = "Example String"replaced = re.sub('[ES]', 'a', s)print replaced 

will print axample atring


As a summary

import sysimport ref = sys.argv[1]find = sys.argv[2]replace = sys.argv[3]with open (f, "r") as myfile:     s=myfile.read()ret = re.sub(find,replace, s)   # <<< This is where the magic happensprint ret