我有一个字符串,其中包含一个服务器文件路径($\MyPath\Quotas\ExactPath\MyFile.txt)和一个本地文件系统路径(C:\MyLocalPath\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);但我希望这是一个不区分大小写的替换,这样它也可以用lPath替换$\MyPath\quotas\Exactpath\。
我遇到了如下正则表达式的使用:
var regex = new Regex( sPath, RegexOptions.IgnoreCase );
var newFPath = regex.Replace( fPath, lPath );但是如何处理特殊字符($、\、/、:),使其不被解释为正则表达式特殊字符?
发布于 2012-11-27 22:11:38
您可以使用Regex.Escape
var regex = new Regex(Regex.Escape(sPath), RegexOptions.IgnoreCase);
var newFPath = regex.Replace(fPath, lPath);发布于 2012-11-27 22:11:41
只需使用Regex.Escape即可
fPath = Regex.Escape(fPath);这将转义所有元字符,并将它们转换为文字。
发布于 2012-11-27 22:30:51
由于您只需要大小写敏感度设置,而不是任何匹配的正则表达式,所以您应该使用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);https://stackoverflow.com/questions/13586026
复制相似问题