1

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?

4
  • 2
    \^ matches a literal ^. Same goes about $. You need to pass flags=re.M to the re.sub and remove the backslashes from ^ and $. And escape the .. See ideone.com/ijPIra Commented Jun 13, 2016 at 20:45
  • Is your_string.replace("test v1.0\n", "upside") too brittle? Commented Jun 13, 2016 at 20:49
  • @jDo I couldn't be 100% sure that replace would work in every situation so I opted for regex (the above script is just pseudo code) Commented Jun 13, 2016 at 20:54
  • @TheGirrafish Makes sense. The regex is more "solid" Commented Jun 13, 2016 at 21:05

1 Answer 1

3

\^ 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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks it works great! I had tried it without the backslashes also but it wouldn't work either. I think the problem was that I was missing the re.M flag the entire time.
Possible. Also, the dot must be escaped to match a literal dot, and not a text like test v1-0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.