String.Replace ignoring case

前端 未结 17 809
野趣味
野趣味 2020-11-29 19:03

I have a string called \"hello world\"

I need to replace the word \"world\" to \"csharp\"

for this I use:

string.Replace(\"World\", \"csharp\         


        
17条回答
  •  没有蜡笔的小新
    2020-11-29 19:53

    Extending Petrucio's answer with Regex.Escape on the search string, and escaping matched group as suggested in Steve B's answer (and some minor changes to my taste):

    public static class StringExtensions
    {
        public static string ReplaceIgnoreCase(this string str, string from, string to)
        {
            return Regex.Replace(str, Regex.Escape(from), to.Replace("$", "$$"), RegexOptions.IgnoreCase);
        }
    }
    

    Which will produce the following expected results:

    Console.WriteLine("(heLLo) wOrld".ReplaceIgnoreCase("(hello) world", "Hi $1 Universe")); // Hi $1 Universe
    Console.WriteLine("heLLo wOrld".ReplaceIgnoreCase("(hello) world", "Hi $1 Universe"));   // heLLo wOrld
    

    However without performing the escapes you would get the following, which is not an expected behaviour from a String.Replace that is just case-insensitive:

    Console.WriteLine("(heLLo) wOrld".ReplaceIgnoreCase_NoEscaping("(hello) world", "Hi $1 Universe")); // (heLLo) wOrld
    Console.WriteLine("heLLo wOrld".ReplaceIgnoreCase_NoEscaping("(hello) world", "Hi $1 Universe"));   // Hi heLLo Universe
    

提交回复
热议问题