【问题标题】:Use RegEx with IgnoreCase to replace a word but replace using correct found word case使用 RegEx 和 IgnoreCase 替换单词,但使用正确找到的单词大小写替换
【发布时间】:2013-08-20 11:31:18
【问题描述】:

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

        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 中,再次解决它时遇到了一些麻烦。

【问题讨论】:

    标签: c# regex replace


    【解决方案1】:
    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.Escape 是一个不错的选择,但为什么不将它与他的 string.Format 一起使用呢? string.Format(@"\b{0}\b", Regex.Escape(word));
    • @Pluc:只是我个人的偏好:String.Format 对于像这样的简单连接来说太过分了,imo。
    • 谢谢卢克,我有一种感觉,就是这么简单!我更喜欢 string.format。
    【解决方案2】:

    以下内容几乎包含您使用 Regex 寻找的内容。唯一的考虑是它保留第一个字符的大小写,所以如果中间有一个大写字母,它看起来不会保留它。

    Replace Text While Keeping Case Intact In C Sharp

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-03
      • 2017-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-27
      • 2018-06-09
      • 1970-01-01
      相关资源
      最近更新 更多