首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >String.Replace方法忽略包含特殊字符的大小写。

String.Replace方法忽略包含特殊字符的大小写。
EN

Stack Overflow用户
提问于 2012-11-27 22:08:43
回答 4查看 1K关注 0票数 1

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

我目前有一个确切的替代方案:

代码语言:javascript
复制
String fPath = @"$\MyPath\Quotas\ExactPath\MyFile.txt";
String sPath = @"$\MyPath\Quotas\ExactPath\";
String lPath = @"C:\MyLocalPath\Quotas\ExactPath\";

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

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

我遇到了如下正则表达式的使用:

代码语言:javascript
复制
var regex = new Regex( sPath, RegexOptions.IgnoreCase );
var newFPath = regex.Replace( fPath, lPath );

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

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-11-27 22:11:38

您可以使用Regex.Escape

代码语言:javascript
复制
var regex = new Regex(Regex.Escape(sPath), RegexOptions.IgnoreCase);
var newFPath = regex.Replace(fPath, lPath);
票数 5
EN

Stack Overflow用户

发布于 2012-11-27 22:11:41

只需使用Regex.Escape即可

代码语言:javascript
复制
fPath = Regex.Escape(fPath);

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

票数 3
EN

Stack Overflow用户

发布于 2012-11-27 22:30:51

由于您只需要大小写敏感度设置,而不是任何匹配的正则表达式,所以您应该使用String.Replace而不是Regex.Replace。令人惊讶的是,没有使用任何区域性或比较设置的Replace方法的重载,但这可以通过扩展方法来修复:

代码语言:javascript
复制
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;
  }

}

用法:

代码语言:javascript
复制
String newPath = fPath.Replace(sPath, lPath, StringComparison.OrdinalIgnoreCase);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13586026

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档