0

So I'm replacing all instances of a word in a string ignoring the case:

        public static String ReplaceAll(String Input, String Word)
    {
        string Pattern = string.Format(@"\b{0}\b", Word);
        Regex rgx = new Regex(Pattern, RegexOptions.IgnoreCase);            
        StringBuilder sb = new StringBuilder();
        sb.Append(rgx.Replace(Input, string.Format("<span class='highlight'>{0}</span>", Word)));
        return sb.ToString();             
    }

What I also need is the replace to keep the found words case, so if I'm looking for 'this' and RegEx finds 'This' it will replace the found word as 'This' and not 'this', I've done this before but it was a few years ago and in javascript, having a little trouble working it out again.

JeffreyJ
  • 99
  • 2
  • 12

2 Answers2

3
public static string ReplaceAll(string source, string word)
{
    string pattern = @"\b" + Regex.Escape(word) + @"\b";
    var rx = new Regex(pattern, RegexOptions.IgnoreCase);
    return rx.Replace(source, "<span class='highlight'>$0</span>");
}
LukeH
  • 263,068
  • 57
  • 365
  • 409
  • Adding the Regex.Escape is a good touch but why not use it with his string.Format? string.Format(@"\b{0}\b", Regex.Escape(word)); – Pluc Aug 20 '13 at 11:41
  • 1
    @Pluc: Just my personal preference: `String.Format` is overkill for simple concatenations like this, imo. – LukeH Aug 20 '13 at 11:44
  • Thanks Luke, I had a feeling it was something simple like that! I prefer the string.format. – JeffreyJ Aug 21 '13 at 04:04
0

The following has pretty much what you're looking for using Regex. The only consideration is that it keeps the case for the first character, so if you have an upper case in the middle it doesn't look like it will keep that.

Replace Text While Keeping Case Intact In C Sharp

Community
  • 1
  • 1
MattR
  • 641
  • 3
  • 17
  • 38