Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Replace [Word] with Word using Regex.Replace and should replace whole word only

Tags:

c#

I'm working on a translation project right now. One of the issues that I encountered is when I'm trying to replace words special characters.

For example:

[Animal] can be furry.
Dog is an [Animal].

I need to replace [Animal] with Animal. Please take note that I need to replace the whole word only. So the result should be as followed:

Animal can be furry.
Dog is an Animal.

Also, as I've said, it should be the whole word. So if i have:

[Animal][Animal][Animal] can be furry. - the result should still be

[Animal][Animal][Animal] can be furry. - nothing happened as [Animal] is not the same as [Animal][Animal][Animal]

Sample:

string originalText1 = "[Animal] can be furry";
string badText ="[Animal]";
string goodText = "Animal";

Regex.Replace(originalText1,  Regex.Escape(badText), Regex.Escape(goodText));

Everything is ok. But as I've said, I need the whole word to be replaced. And with the above code, "[Animal]can be furry" will be replaced by "Animalcan be furry" which is a no no.

so I also tried:

Regex.Unescape(
 Regex.Replace(
  Regex.Escape(originalText1), 
  String.Format(@"\b{0}\b", Regex.Escape(badText)), 
  Regex.Escape(goodText)))

Still won't work though. And now I'm lost. Please help.

I'd also like to mention that there's an ALMOST similar post, but that question didn't require the replacement of whole word only. I've looked over the net for almost 3 hours to no avail. Your help will be greatly appreciated. Thanks!

like image 785
Jeju Avatar asked Oct 15 '12 11:10

Jeju


1 Answers

I haven't tested it, but I would try this:

Regex.Replace(orginalText, @"\b\[Animal\]\b", "Animal");

That would only match [Animal] at word boundaries (\b)

like image 124
Philippe Leybaert Avatar answered Oct 22 '22 21:10

Philippe Leybaert