将RegEx与IgnoreCase一起使用可以替换单词,但要使用找到的正确单词大小写进行替换

本文关键字:替换 单词 大小写 IgnoreCase RegEx 一起 | 更新日期: 2023-09-27 18:28:16

因此,我将替换字符串中单词的所有实例,忽略大小写:

        public static String ReplaceAll(String Input, String Word)
    {
        string Pattern = string.Format(@"'b{0}'b", Word);
        Regex rgx = new Regex(Pattern, RegexOptions.IgnoreCase);            
        StringBuilder sb = new StringBuilder();
        sb.Append(rgx.Replace(Input, string.Format("<span class='highlight'>{0}</span>", Word)));
        return sb.ToString();             
    }

我还需要的是替换来保持查找到的单词的大小写,所以如果我在寻找"this",RegEx找到"this",它会将查找到的词替换为"this’而不是"this"。我以前也这样做过,但这是几年前的事了,在javascript中,再次计算时有点麻烦。

将RegEx与IgnoreCase一起使用可以替换单词,但要使用找到的正确单词大小写进行替换

public static string ReplaceAll(string source, string word)
{
    string pattern = @"'b" + Regex.Escape(word) + @"'b";
    var rx = new Regex(pattern, RegexOptions.IgnoreCase);
    return rx.Replace(source, "<span class='highlight'>$0</span>");
}

下面是您使用Regex所要查找的内容。唯一需要考虑的是,它保留了第一个字符的大小写,所以如果你在中间有一个大写,它看起来不会保留这个大小写。

在C Sharp 中保持大小写完整的同时替换文本