首页 > 解决方案 > 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".

标签: c#regexstringreplaceall

解决方案


我建议使用Linq,而不是常规表达式

using System.Linq;

...

public static string ReplaceAll(
  string str, char[] charsToReplace, char replacementCharacter) 
{
   // Please, note IsNullOrEmpty syntax
   // we should validate charsToReplace as well
   if (string.IsNullOrEmpty(str) || null == charsToReplace || charsToReplace.Length <= 0)
     return str; // let's just do nothing (say, not turn null into empty string)

   return string.Concat(str.Select(c => charsToReplace.Contains(c) 
     ? replacementCharacter
     : c));
}

如果你坚持Regex(注意,我们应该Regex.Escape在 chars 内charsToReplace)。但是,根据手册 Regex.Escape 并没有转义 -,并且在正则表达式括号[内具有特殊含义

public static string ReplaceAll(
  string str, char[] charsToReplace, char replacementCharacter) {

  if (string.IsNullOrEmpty(str) || null == charsToReplace || charsToReplace.Length <= 0)
    return str;

  string charsSet = string.Concat(charsToReplace
    .Select(c => new char[] { ']', '-' }.Contains(c) // in case of '-' and ']'
       ? $@"\{c}"                                    // escape them as well
       : Regex.Escape(c.ToString())));

  return Regex.Replace(
     str,
    $"[{charsSet}]+",
     m => new string(replacementCharacter, m.Length));
}

推荐阅读