The Question :
455 people think this question is useful
I have a parameter file of the form:
Where the parameters may be in any order but there is only one parameter per line. I want to replace one parameter’s
parameter-value with a new value.
I am using a line replace function posted previously to replace the line which uses Python’s
string.replace(pattern, sub). The regular expression that I’m using works for instance in vim but doesn’t appear to work in
Here is the regular expression that I’m using:
line.replace("^.*interfaceOpDataFile.*$/i", "interfaceOpDataFile %s" % (fileIn))
"interfaceOpDataFile" is the parameter name that I’m replacing (/i for case-insensitive) and the new parameter value is the contents of the
Is there a way to get Python to recognize this regular expression or else is there another way to accomplish this task?
The Question Comments :
The Answer 1
608 people think this answer is useful
str.replace() v2|v3 does not recognize regular expressions.
To perform a substitution using a regular expression, use
line = re.sub(
"interfaceOpDataFile %s" % fileIn,
In a loop, it would be better to compile the regular expression first:
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
The Answer 2
420 people think this answer is useful
You are looking for the re.sub function.
s = "Example String"
replaced = re.sub('[ES]', 'a', s)
The Answer 3
16 people think this answer is useful
As a summary
f = sys.argv
find = sys.argv
replace = sys.argv
with open (f, "r") as myfile:
ret = re.sub(find,replace, s) # <<< This is where the magic happens
The Answer 4
10 people think this answer is useful
re.sub is definitely what you are looking for. And so you know, you don’t need the anchors and the wildcards.
re.sub(r"(?i)interfaceOpDataFile", "interfaceOpDataFile %s" % filein, line)
will do the same thing–matching the first substring that looks like “interfaceOpDataFile” and replacing it.