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.

2 Answers 2

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>");
}
Sign up to request clarification or add additional context in comments.

3 Comments

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: Just my personal preference: String.Format is overkill for simple concatenations like this, imo.
Thanks Luke, I had a feeling it was something simple like that! I prefer the string.format.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.