0

I'm trying replace a block of text inside of tags with python sub.

Block of text:

text = """##startBlablaTag##
          blablabla
          blebleble
          bliblibli
          ##endtBlablaTag##

Using the following regexp with "search" I can catch what's inside of the tags

>>> re.search(r'^##\w+Blabla\w+##\n(.*)##\w+Blabla\w+##', text, re.MULTILINE | re.DOTALL).group(1)
'blablabla\blebleble\bliblibli\n'
>>> 

but when I try with "sub" to replace, I can't replace the whole content, just the end...

>>> re.sub(r'^##\w+Blabla\w+##\n(.*)##\w+Blabla\w+##', r'\g<1>test!', text, flags=re.MULTILINE | re.DOTALL)
'blablabla\nblebleble\nbliblibli\ntest!'

Expected:

##startBlablaTag##
test!
##endtBlablaTag##

Anybody knows how to replace the whole content inside the tags?

Thanks!

1
  • @Aran-Fey sorry, post edited. Commented Mar 27, 2018 at 21:29

1 Answer 1

1

You're doing it backwards.

The regex you used is this:

^##\w+Blabla\w+##\n(.*)##\w+Blabla\w+##

As you can see, you have used a capture group to capture the text inside of the tag. In other words, you've captured the text that you want to remove. This serves no purpose - you should be using capture groups around the text that you want to keep. In other words, the regex should look like this:

^(##\w+Blabla\w+##\n).*(##\w+Blabla\w+##)

Now you can use backreferences to refer to the captured text during the substitution and insert new text inside of the tags:

>>> re.sub(r'^(##\w+Blabla\w+##\n).*(##\w+Blabla\w+##)', r'\1test!\2', text, flags=re.S)
'##startBlablaTag##\ntest!##endtBlablaTag##'
Sign up to request clarification or add additional context in comments.

Comments

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.