How Replace a string in regex

Hello Community,

I want to replace a word (loves) with another word (hates) by using regex, such that i just replace the text content and not the values in the Tags.

Input:

<li>My dog loves dog food</li>
<li class="loves"> My dog loves dog food</li>

Output:

<li>My dog **hates** dog food</li>
<li class="loves"> My dog **hates** dog food</li>

I tried using this regex with replace but it replaces the entire phrase
>(.?)(loves)(.?)</

Can someone help me with it?

Any other approaches will be highly appreciated!

Thanks.

Hi @hansen_Lobo

You can use simple string manipulations as well:
StringName.Replace(β€œloves”,β€œhates”)

This should work too.

1 Like

if i do this:

<li>My dog loves dog food</li>
<li class="**loves**"> My dog loves dog food</li>

The highlighted one will also get changed. I dont want it to change

Try this

System.Text.RegularExpressions.Regex.Replace(strOriginal, "[^""]loves[^""]", " hates ")

You will get something like this:

image

Hi,

FYI, Another pattern:

System.Text.RegularExpressions.Regex.Replace(yourString,"(?<=\s)loves(?=\s)","hates")

Regards,

1 Like

But more recomended to process HTML with https://html-agility-pack.net/

1 Like

Thanks Peter,
This works really well!!

Will look into this soon

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.