1

So I have this:

z='===hello  
there===,  
how are ===you===?'

And I want to be:

z='<b>hello  
there<\b>,  
how are <b>you<\b>?'

I tried doing this:

z = re.sub(r"\={3}([^\$]+)\={3}", r"<b> \\1 </b>", z, re.M)  

And it works sort of but I got this instead:

z='<b>hello  
there===,  
how are ===you<\b>?'  

I'm still new to this but I believe it's the ^ and $ that makes it match the beginning and the end of the string. So how do I change it so it matches the ones in the middle?

1
  • Use 4 spaces or <CTRL>-<K> To indent code Commented May 13, 2013 at 9:06

1 Answer 1

2
re.sub(r"\={3}([^\$]+?)\={3}", r"<b> \\1 </b>", z, re.M)

Copy from python docClick Here:

*?, +?, ?? The '*', '+', and '?' qualifiers are all greedy; they match as much text as possible. Sometimes this behaviour isn’t desired; if the RE <.*> is matched against '<H1>title</H1>', it will match the entire string, and not just '<H1>'. Adding '?' after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using .*? in the previous expression will match only '<H1>'.

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

2 Comments

Please explain why this fixes the OPs problem, so he knows in the future. (It's because +? is lazy and matches as few characters as possible, so it stops at the first <\b> not the last <\b>)
Oh I see. And it worked! It also fixed another problem I had so thanks!

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.