我有一个名为hello world的字符串
我需要把"world"换成" chsharp "
我用:
string.Replace("World", "csharp");
但结果是,字符串没有被替换。原因在于区分大小写。原来的字符串包含“世界”,而我试图取代“世界”。
有没有办法避免字符串中的这种区分大小写的情况?替代方法?
我有一个名为hello world的字符串
我需要把"world"换成" chsharp "
我用:
string.Replace("World", "csharp");
但结果是,字符串没有被替换。原因在于区分大小写。原来的字符串包含“世界”,而我试图取代“世界”。
有没有办法避免字符串中的这种区分大小写的情况?替代方法?
当前回答
用Regex扩展Petrucio的答案。在搜索字符串上转义,并在Steve B的回答中建议转义匹配的组(和一些小的改变,我的口味):
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);
}
}
这将产生以下预期结果:
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
然而,如果不执行转义,您将得到以下结果,这不是String的预期行为。替换是不区分大小写的:
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
其他回答
你可以使用Regex并执行不区分大小写的替换:
class Program
{
static void Main()
{
string input = "hello WoRlD";
string result =
Regex.Replace(input, "world", "csharp", RegexOptions.IgnoreCase);
Console.WriteLine(result); // prints "hello csharp"
}
}
(编辑:没有意识到“裸链接”的问题,对不起)
从这里开始:
string myString = "find Me and replace ME";
string strReplace = "me";
myString = Regex.Replace(myString, "me", strReplace, RegexOptions.IgnoreCase);
似乎你不是第一个抱怨字符串不区分大小写的人。
下面的函数是从字符串集中删除所有匹配的单词(this)。作者:Ravikant Sonare。
private static void myfun()
{
string mystring = "thiTHISThiss This THIS THis tThishiThiss. Box";
var regex = new Regex("this", RegexOptions.IgnoreCase);
mystring = regex.Replace(mystring, "");
string[] str = mystring.Split(' ');
for (int i = 0; i < str.Length; i++)
{
if (regex.IsMatch(str[i].ToString()))
{
mystring = mystring.Replace(str[i].ToString(), string.Empty);
}
}
Console.WriteLine(mystring);
}
你可以用微软。VisualBasic命名空间来查找这个帮助函数:
Replace(sourceString, "replacethis", "withthis", , , CompareMethod.Text)
您还可以尝试Regex类。
var regex = new regex ("camel", RegexOptions. var regex = new regex。IgnoreCase); var newSentence =正则表达式。替换(句子,“马”);