regex – Python string.replace regular expression
regex – Python string.replace regular expression
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 re
line = re.sub(
r(?i)^.*interfaceOpDataFile.*$,
interfaceOpDataFile %s % fileIn,
line
)
In a loop, it would be better to compile the regular expression first:
import re
regex = 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 re
s = Example String
replaced = re.sub([ES], a, s)
print replaced
will print axample atring
regex – Python string.replace regular expression
As a summary
import sys
import re
f = 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 happens
print ret