Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python string.replace regular expression [duplicate]

I have a parameter file of the form:

parameter-name parameter-value 

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 string.replace().

Here is the regular expression that I'm using:

line.replace("^.*interfaceOpDataFile.*$/i", "interfaceOpDataFile %s" % (fileIn)) 

Where "interfaceOpDataFile" is the parameter name that I'm replacing (/i for case-insensitive) and the new parameter value is the contents of the fileIn variable.

Is there a way to get Python to recognize this regular expression or else is there another way to accomplish this task?

like image 853
Troy Rockwood Avatar asked May 23 '13 17:05

Troy Rockwood


2 Answers

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

like image 28
Jacek Przemieniecki Avatar answered Sep 21 '22 06:09

Jacek Przemieniecki


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 
like image 130
Andrew Clark Avatar answered Sep 20 '22 06:09

Andrew Clark