C# .NET类库自带的str.Replace() 方法替换文本不能区分大小写。
我们可以自己编写一个扩展方法,支持文本忽略大小写替换。
以下扩展方法实现了使用正则表达式忽略大小写替换文本。
public static string ReplaceText(this string text, string find, string replacement, bool caseSensitive = false, int startAt = 0, int count = -1)  // 正则替换字符串
{
	try
	{
		System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(System.Text.RegularExpressions.Regex.Escape(find), (caseSensitive ? System.Text.RegularExpressions.RegexOptions.None : System.Text.RegularExpressions.RegexOptions.IgnoreCase));
		return (regex.Replace(text, replacement, count, startAt));
	}
	catch (Exception)
	{
		return (text);
	}
}  
知乎: @张赐荣
赐荣博客: www.prc.cx
 
                    
                 
                
 
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号