[英]String.Replace method ignores case with special characters.
我有一個包含服務器文件路徑($ \\ 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);
因為只需要區分大小寫設置,而不需要任何正則表達式匹配,所以您應該使用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
比使用Regex.Replace
快10-15倍。
我建議完全不要使用“替換”。 使用System.IO中的Path類:
string fPath = @"$\MyPath\Quotas\ExactPath\MyFile.txt";
string lPath = @"C:\MyLocalPath\Quotas\ExactPath\";
string newPath = Path.Combine(lPath, Path.GetFileName(fPath));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.