【问题标题】:String.Replace method ignores case with special characters.String.Replace 方法忽略特殊字符的大小写。
【发布时间】:2012-11-15 04:19:00
【问题描述】:

我有一个包含服务器文件路径 ($\MyPath\Quotas\ExactPath\MyFile.txt) 和本地文件系统路径 (C:\MyLocalPath\Quotas\ExactPath) 的字符串。我想用本地系统路径替换服务器文件路径。

我目前有一个确切的替换:

String fPath = @"$\MyPath\Quotas\ExactPath\MyFile.txt";
String sPath = @"$\MyPath\Quotas\ExactPath\";
String lPath = @"C:\MyLocalPath\Quotas\ExactPath\";

String newPath = fPath.Replace(sPath, lPath);

但我希望这是一个不区分大小写的替换,以便它也可以将 $\MyPath\quotas\Exactpath\ 替换为 lPath。

我遇到过以下正则表达式的用法:

var regex = new Regex( sPath, RegexOptions.IgnoreCase );
var newFPath = regex.Replace( fPath, lPath );

但是如何处理特殊字符($,\,/,:) 使其不被解释为正则表达式特殊字符呢?

【问题讨论】:

    标签: c# regex string replace


    【解决方案1】:

    我建议根本不要使用 Replace。在 System.IO 中使用 Path 类:

    string fPath = @"$\MyPath\Quotas\ExactPath\MyFile.txt";
    string lPath = @"C:\MyLocalPath\Quotas\ExactPath\";
    
    string newPath = Path.Combine(lPath, Path.GetFileName(fPath));
    

    【讨论】:

      【解决方案2】:

      由于您只是在区分大小写设置之后,而不是任何正则表达式匹配,您应该使用String.Replace 而不是Regex.Replace。令人惊讶的是,没有采用任何文化或比较设置的 Replace 方法的重载,但可以使用扩展方法修复:

      public static class StringExtensions {
      
        public static string Replace(this string str, string match, string replacement, StringComparison comparison) {
          int index = 0, newIndex;
          StringBuilder result = new StringBuilder();
          while ((newIndex = str.IndexOf(match, index, comparison)) != -1) {
            result.Append(str.Substring(index, newIndex - index)).Append(replacement);
            index = newIndex + match.Length;
          }
          return index > 0 ? result.Append(str.Substring(index)).ToString() : str;
        }
      
      }
      

      用法:

      String newPath = fPath.Replace(sPath, lPath, StringComparison.OrdinalIgnoreCase);
      

      测试性能,这比使用Regex.Replace快10-15倍。

      【讨论】:

        【解决方案3】:

        只需使用Regex.Escape:

        fPath = Regex.Escape(fPath);
        

        这会转义所有元字符并将它们转换为文字。

        【讨论】:

        • 在使用 var regex 和 var newFPath 的示例中,我想转义 sPath、fPath、AND lPath,还是只转义 fPath?
        • @John Escape 你用来构建正则表达式的那个。所以在你的情况下,你会逃避sPath
        【解决方案4】:

        你可以使用Regex.Escape:

        var regex = new Regex(Regex.Escape(sPath), RegexOptions.IgnoreCase);
        var newFPath = regex.Replace(fPath, lPath);
        

        【讨论】:

        • 在使用 var regex 和 var newFPath 的示例中,我想转义 sPath、fPath、AND lPath,还是只转义 sPath?
        • @John,就是您用作正则表达式的那个 - sPath 在您的情况下。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-08-26
        • 2020-06-13
        • 1970-01-01
        • 2013-12-11
        • 2023-03-22
        • 1970-01-01
        • 2017-07-30
        相关资源
        最近更新 更多