0

I have a python pattern that I want to replace in two different ways.

Pattern: <br><b>[Ss][1-2]:[0-9]*-
1)replace by " "
2)replace s/S by Author

I can do the first one as it is a simple replacement, but I am not sure how can I do the second replacement as it depends upon input pattern and only a part of the expression has to be replaced.

This is working for case 1, where I just replace by blanks.

text="<br><b>S1:2- you are wrong. I don't think so. <br><b>S2:2- you are wrong"
newtext=re.sub("(<br><b>[Ss][1-2]:[0-9]*-)\s*", ' ',text)
print(newtext)

Can we have a variable expression in the replacement string?

Replaced text

<br><b>Author1:2- you are wrong. I don't think so. <br><b>Author2:2- you are wrong
1
  • can you give a sample replacement for the second use case Commented Feb 27, 2017 at 18:44

1 Answer 1

4

You may use look-around syntax:

import re
text="<br><b>S1:2- you are wrong. I don't think so. <br><b>S2:2- you are wrong"
re.sub("(?<=<br><b>)[Ss](?=[1-2]:[0-9]*-\s*)", 'Author',text)
# "<br><b>Author1:2- you are wrong. I don't think so. <br><b>Author2:2- you are wrong"
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.