2012-11-27 106 views
1

我有一個包含服務器文件路徑($ \ MyPath \ Quotas \ ExactPath \ MyFile.txt)和本地文件系統路徑(C:\ MyLocalPath \ Quotas \ ExactPath)的字符串。我想用本地系統路徑替換服務器文件路徑。String.Replace方法忽略具有特殊字符的大小寫。

我現在有一個確切的更換:

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中\配額\ Exactpath \爲好。

我整個使用正則表達式像來到了以下內容:

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

但我怎麼處理特殊字符($,\,/,:),使其不被解釋爲一個正則表達式特殊字符?

回答

5

您可以使用Regex.Escape

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

與VAR正則表達式和VAR newFPath的例子中,我會想逃避SPATH,fPath,和LPATH,或者只是SPATH? – jkh

+0

@John,就是你正在使用的正則表達式 - 'sPath'。 – Andrei

3

只需使用Regex.Escape

fPath = Regex.Escape(fPath); 

這一切逃逸元字符,並把它們轉化成文字。

+0

在var regex和var newFPath的例子中,我想轉義sPath,fPath,AND lPath,還是隻是fPath? – jkh

+0

@John轉義你正在使用的構造你的正則表達式。所以在你的情況下你會轉義'sPath'。 –

0

由於您只是在大小寫感應設置之後,而不是任何正則表達式匹配,您應該使用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倍。

0

我會建議不要使用Replace。使用在System.IO的路徑類:

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

string newPath = Path.Combine(lPath, Path.GetFileName(fPath));