2015-02-10 218 views
1

我想知道什麼是避免在字符串中反斜槓的好方法,而不會增加不必要的斜線。在字符串中跳出反斜槓

我的意思是,平時如果我想逃避字符串中的反斜槓,最簡單的方法是使用String.Replace()像這樣:

string s = someString.Replace("\\", "\\\\");

類似的事情可以使用Regex.Replace()正則表達式完成。

現在的問題是,可以說我有了一些反斜槓逃脫類似的字符串,例如:"C:\some_folder\\some_file.bin"

現在,如果我嘗試和每次出現之前添加一個反斜槓替換的反斜槓,我將結束與以下字符串:

"C:\\some_folder\\\\some_file.bin"

沒有明確的\\\\是不必要的,讓我怎麼去忽視已經轉義字符?

+1

@DmitryBychenko誰說過'\ t'什麼? – 2015-02-10 07:36:24

+0

您是否嘗試過任何解決方案? – fubo 2015-02-12 14:58:40

回答

2

我想,這是你想要做 -

string path = @"C:\some_folder\\some_file.bin"; 
    string exactPath = string.Join("\\",path.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries)); 
1

這裏什麼是正則表達式的方法

string Result = Regex.Replace("C:\\some_folder\\\\some_file.bin", "[\\\\]+", "\\"); 

在你需要逃脫正則表達式和C#的話。或者你可以寫

string Result = Regex.Replace(@"C:\some_folder\\some_file.bin",@"[\\]+",@"\"); 

因爲"\\"等於@"\"