-1

I need to replace only if the string has an exact match. How can I do this ?

At the moment it replaces the string expression if it matches any part of the string.

string strExpression  = "hey! Hello World. SpecialDayForMe";

strExpression = strExpression .Replace("SpecialDay", "ABC") ;

The result of the strExpression is "hey! Hello World. ABCForMe".

What I want it to ONLY match if there's a match of SpecialDay in the string and not for a partial match. How can I do this ?

Note: Would be great if I can do this without using REGEX.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Illep
  • 16,375
  • 46
  • 171
  • 302
  • 2
    What is an exact match? Is `Specialday;forMe` exact or `special-day.ForMe`? – Tim Schmelter Dec 17 '18 at 08:59
  • 2
    Please clarify your question significantly - talk about an "exact match" sounds like you're distinguishing between matches that vary in case, etc. "hey! Hello World. SpecialDayForMe" does contain *exactly* "SpecialDay". I believe you're really interested in whether it's a match for a complete word. For that, you'll need to come up with detailed requirements. How do you want hyphens and other punctuation to behave? Do you have a precise list of characters that are allowed before/after the token you're trying to match? – Jon Skeet Dec 17 '18 at 09:03
  • 5
    Possible duplicate of [Way to have String.Replace only hit "whole words"](https://stackoverflow.com/questions/6143642/way-to-have-string-replace-only-hit-whole-words) – marsze Dec 17 '18 at 09:04
  • This might help https://www.codeproject.com/Questions/644729/Find-Replace-exact-Words-in-Csharp – Vishwa Ratna Dec 17 '18 at 09:04
  • 3
    Is there any particular reason you want to do this without regex? I don't think there's another way which wouldn't involve doing some parsing on your own, basically building your own little regex engine for this purpose. – marsze Dec 17 '18 at 09:09

1 Answers1

5

When replacing whole words, try using regular expressions (\b to mark word's border):

 using System.Text.RegularExpressions;

 ...

 string strExpression  = "hey! Hello World. SpecialDayForMe";
 string toFind = "SpecialDay";

 strExpression = Regex.Replace(
   strExpression, 
  @"\b" + Regex.Escape(toFind) + @"\b", // Regex.Escape to be on the safe side
   "ABC");

It matches "Hello world. SpecialDay for me" as well as "SpecialDay," and "SpecialDay.".

Mikael Dúi Bolinder
  • 2,080
  • 2
  • 19
  • 44
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215