Search code examples
c#regexstringreplaceall

How to replace all given characters?


I'm trying to write a method that replaces all occurrences of the characters in the input array (charsToReplace) with the replacementCharacter using regex. The version I have written does not work if the array contains any characters that may change the meaning of the regex pattern, such as ']' or '^'.

public static string ReplaceAll(string str, char[] charsToReplace, char replacementCharacter)
{
    if(str.IsNullOrEmpty())
    {
        return string.Empty;
    }

    var pattern = $"[{new string(charsToReplace)}]";
    return Regex.Replace(str, pattern, replacementCharacter.ToString());
}

So ReplaceAll("/]a", {'/', ']' }, 'a') should return "aaa".


Solution

  • Inside a character class, only 4 chars require escaping, ^, -, ] and \. You can't use Regex.Escape because it does not escape -and ] as they are not "special" outside a character class. Note that Regex.Escape is meant to be used only for literal char (sequences) that are outside character classes.

    An unescaped ] char will close your character class prematurely and that is the main reason why your code does not work.

    So, the fixed pattern variable definition can look like

    var pattern = $"[{string.Concat(charsToReplace).Replace(@"\", @"\\").Replace("-", @"\-").Replace("^", @"\^").Replace("]", @"\]")}]";
    

    See an online C# demo.