TheGirrafish TheGirrafish - 5 months ago 12
Python Question

Python - Find and replace regex substring in a string variable

I have a variable with a multiline string and I'm trying to replace the line

test v1.0
with
upside
but the problem is I'm trying to replace it only if the entire line matches the pattern so it shouldn't replace the first
test v1.0.1


pkgLogExtract = dedent("""
test v1.0.1
nothing

test v1.0
out
in
flip
""")

print (re.sub(r'\^test v1.0\$', "upside", pkgLogExtract, 1))


I tried using
re.sub
and putting
'\^test v1.0\$'
as the pattern to replace but it doesn't replace anything. I've also tried it with the raw flag, so
r'\^test v1.0\$'
but that doesn't replace anything either. Any idea what I could do?

Answer

\^ matches a literal ^. Same goes about $. You need to pass flags=re.M to the re.sub and remove the backslashes from ^ and $ so that they could match the start and end of line respectively. And escape the ..

See this IDEONE demo:

import re
pkgLogExtract = """
test v1.0.1
nothing
test v1.0
out
in
flip
"""

print (re.sub(r'^test v1\.0$', "ngn", pkgLogExtract, 1, flags=re.M))

Note: I think you know that 1 stands for a single replacement (only the first match will get replaced).

Note 2: you may omit flags= and use re.M, but a lot of people forget to use the above mentioned count argument, so it is best to keep the argument name here.