Case insensitive string replace

string.Replace() is case sensitive. Regex.Replace isn't, though...

using System.Text.RegularExpressions;

string myString = "find Me and replace ME";
string strReplace = "me";

myString = Regex.Replace(myString, "me", strReplace, RegexOptions.IgnoreCase);
Obvious, but somehow I keep forgetting it... It'd be nice if string.Replace learned this trick some day.

13 Comments

  • Note that the replaced text must be escaped it if contains any special regex characters.

  • Good catch, Raymond. Looks like that code should be using Regex.Escape() on the appropriate strings.

  • Nice... It is working perfect with Escape() and UnScape()

  • string text = @",\\127.0.0.1\rawdata\noname\yark\coucou.txt,,,,2,1";
    string orig = @"\\127.0.0.1\rawdata\noname\";
    string replace = @"c:\titi\dupond\";

    string result = Regex.Replace(text, Regex.Escape(orig), replace, RegexOptions.IgnoreCase);

  • Very good!! Working fine!

  • Excellent article. Thanks

  • static public string Replace(string original, string pattern, string replacement, StringComparison comparisonType)
    {
    if (original == null)
    {
    return null;
    }

    if (String.IsNullOrEmpty(pattern))
    {
    return original;
    }

    int lenPattern = pattern.Length;
    int idxPattern = -1;
    int idxLast = 0;

    StringBuilder result = new StringBuilder();

    while (true)
    {
    idxPattern = original.IndexOf(pattern, idxPattern + 1, comparisonType);

    if (idxPattern < 0)
    {
    result.Append(original, idxLast, original.Length - idxLast);

    break;
    }

    result.Append(original, idxLast, idxPattern - idxLast);
    result.Append(replacement);

    idxLast = idxPattern + lenPattern;
    }

    return result.ToString();
    }

  • maheshsingh's function is great!. It just saved my ass!!

  • Thanks man was looking exactly for this method :).

  • Wonderful,

    I was using RegEx to achieve this but was missing Escape().

    Now it works great.

    Thanks to the person who wrote second comment, right at the top.

  • Maheshsingh, nice Replace() function, a lot like VB.net. I would add only one thing to your code. If no replacements are made to the original string, just return the original string instead of making a copy. It is safe to return the original string, especially since strings are immutable.

    if (idxPattern < 0)
    {
    if (result.Length == 0) return original; //added this line
    result.Append(original, idxLast, original.Length - idxLast);
    break;
    }

  • .net fast replace case insensitive

    https://sourceforge.net/projects/replacecaseinse/

  • Pretty! This has been an tremendously fantastic item. A lot of recognition for providing this information.

Comments have been disabled for this content.