Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Replace an Undetermined length of Text

I have a string like this:

Hi. My name is _John_. I am _20_ years old.

and I'd like to convert it into this:

Hi. My name is <b>John</b>. I am <b>20</b> years old.

I did something like this but no luck.

import re
text = "Hi. My name is _John_. I am _20_ years old."
pattern = "(.*)(\_)(.*)(\_)(.*)"
re.sub(pattern, r'\1<b>\3</b>\5', text)
'Hi. My name is _John_. I am <b>20</b> years old.'

What is wrong with the pattern? Why is it not seeing the first bold text?

Any help would be appreciated. Thanks.

like image 646
Ozgur Vatansever Avatar asked Dec 01 '25 05:12

Ozgur Vatansever


1 Answers

Change to:

pattern = "_([^_]*)_"
re.sub(pattern, r'<b>\1</b>', text)

Also see this example.

like image 128
scessor Avatar answered Dec 03 '25 21:12

scessor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!