Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exact word replace in content using Python

I am trying to replace some content using regular expression. I am able to do that using the following method:

EX: """ The search technique is usefull, the search technique is usefull """
old = 'the'
toreplace = "<span class='highlight' STYLE='background-color:yellow'>" +  old + "</span>"
pattern = re.compile(re.escape(old), re.I)
highlighted_txt = re.sub(pattern,toreplace,A,count)

" <span class='highlight' STYLE='background-color:yellow'>the</span> search tech
nique is usefull, <span class='highlight' STYLE='background-color:yellow'>the</s
pan> search technique is usefull "

But what I want to do is replace the old word with what is found exactly in the content. Like the second "The" should be replaced with

<span class='highlight' STYLE='background-color:yellow'>The</span>

" <span class='highlight' STYLE='background-color:yellow'>the</span> search tech
nique is usefull, <span class='highlight' STYLE='background-color:yellow'>The</s
pan> search technique is usefull "
like image 379
Rakesh Avatar asked Aug 29 '26 23:08

Rakesh


1 Answers

When using re.sub you can put \0 in the replacement string which will be expanded into the match of the search expression. You need to be sure that the \0 is not interpreted as an octal escape, so it is convenient to use a raw string literal. For example, you can change the third line of your code to

toreplace = r"<span class='highlight' STYLE='background-color:yellow'>\0</span>"

and you should get the behavior you are looking for.

Since you want to use the entire matched string, you do not need to create any groups in your regular expression. The 0 group is always defined as the entire matched string.

like image 147
Geoff Reedy Avatar answered Aug 31 '26 18:08

Geoff Reedy



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!