Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python regular expression replacing part of a matched string

i got an string that might look like this

"myFunc('element','node','elementVersion','ext',12,0,0)"

i'm currently checking for validity using, which works fine

myFunc\((.+?)\,(.+?)\,(.+?)\,(.+?)\,(.+?)\,(.+?)\,(.+?)\)

now i'd like to replace whatever string is at the 3rd parameter. unfortunately i cant just use a stringreplace on whatever sub-string on the 3rd position since the same 'sub-string' could be anywhere else in that string.

with this and a re.findall,

myFunc\(.+?\,.+?\,(.+?)\,.+?\,.+?\,.+?\,.+?\)

i was able to get the contents of the substring on the 3rd position, but re.sub does not replace the string it just returns me the string i want to replace with :/

here's my code

myRe = re.compile(r"myFunc\(.+?\,.+?\,(.+?)\,.+?\,.+?\,.+?\,.+?\)")
val =   "myFunc('element','node','elementVersion','ext',12,0,0)"

print myRe.findall(val)
print myRe.sub("noVersion",val)

any idea what i've missed ?

thanks! Seb

like image 871
Seb Avatar asked Dec 20 '10 11:12

Seb


People also ask

How do you replace a specific part of a string with something else Python?

Python String | replace() The replace() in Python returns a copy of the string where all occurrences of a substring are replaced with another substring.

How do you replace a matching string in Python?

To replace a string in Python, the regex sub() method is used. It is a built-in Python method in re module that returns replaced string. Don't forget to import the re module. This method searches the pattern in the string and then replace it with a new given expression.

How do you replace all occurrences of a regex pattern in a string in Python?

sub() method will replace all pattern occurrences in the target string. By setting the count=1 inside a re. sub() we can replace only the first occurrence of a pattern in the target string with another string. Set the count value to the number of replacements you want to perform.


1 Answers

In re.sub, you need to specify a substitution for the whole matching string. That means that you need to repeat the parts that you don't want to replace. This works:

myRe = re.compile(r"(myFunc\(.+?\,.+?\,)(.+?)(\,.+?\,.+?\,.+?\,.+?\))")
print myRe.sub(r'\1"noversion"\3', val)
like image 184
Martin v. Löwis Avatar answered Oct 04 '22 21:10

Martin v. Löwis