我有一个包含服务器文件路径($ \ 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);
但是我希望这是不区分大小写的替换,以便它也可以用lPath替换$ \ MyPath \ quotas \ Exactpath \。
我发现正则表达式的用法如下:
var regex = new Regex( sPath, RegexOptions.IgnoreCase );
var newFPath = regex.Replace( fPath, lPath );
但是,如何处理特殊字符($,\,/,:),使其不被解释为正则表达式特殊字符?
最佳答案
您可以使用Regex.Escape:
var regex = new Regex(Regex.Escape(sPath), RegexOptions.IgnoreCase);
var newFPath = regex.Replace(fPath, lPath);