2017-03-05 90 views
-2

採取以下字符串作爲輸入:從字符串中提取一個文件路徑或文件名在C#

var input = @"The file is: ""c:\sampleDirectory\sample subdirectory\sampleFileName.txt\"" which is a text file"; 

我如何可以提取只能從上面的字符串的文件路徑。
使用正則表達式或類似的方法是首選。

+0

剛上它最終反斜線和分裂的指標.. –

+0

.Substring之間閱讀「」這你有.IndexOf –

+3

確定的位置你真的需要使它與正則表達式複雜嗎?爲什麼不使用System.IO中的Path.GetFileName,Path.GetDirectoryName等(我相信它也是操作系統友好的) – shunty

回答

1

編輯:

它可與LastIndexOf來完成的回答eocron。

但這裏是一個正則表達式的解決方案:

Match match = Regex.Match(input, @"""(.*)\\(.*\..*)[\\]?""", RegexOptions.IgnoreCase); 

if (match.Success) 
{ 
    string path = match.Groups[1].Value; 
    string filename = match.Groups[2].value; 
} 
+0

我意識到這個問題顯然有一個Windows路徑,但如果您確實必須使用正則表達式或LastIndexOf而不是System中的內置操作,則應該使用Path.DirectorySeparatorChar。 IO.Path – shunty

+0

你給出的解決方案給出了完全錯誤的結果:[https://dotnetfiddle.net/eYzJsT](https://dotnetfiddle.net/eYzJsT) –

+0

@MostafaArmandi我以爲引號內的字符串只是無論如何,我已經像你想要的那樣做了,也編輯了答案。這就是你想要的https://dotnetfiddle.net/iz9Lmv – Zeus

-2

如果你的輸入模式看起來完全一樣,你可以很容易地做到這一點沒有正則表達式:

var magic1 = 14;//index of first quotation mark 
var magic2 = 22;//suffix index of last quotation mark 
var result = str.Substring(magic, str.Lenght-magic2-magic1); 
+0

魔術答案不適用於SO:[當然實際文件不是「sampleFileName.txt」 – Slai

+0

您可以通過添加代碼來生成結果(所以它更通用) –

相關問題