2012-08-30 49 views
2

我有遵循下面的模式文件路徑:如何獲取此文件路徑的最後部分?

一些\文件\路徑\基地\ YYYY \ MM \ DD \ HH \毫米\ Random8.3

我想從2012年及以後的一切提取,但問題是,雖然右側是標準的,但每個記錄的基本目錄可能不同。

下面是兩個例子:

  1. C:\ TEMP \ X \ 2012 \ 08 \ 27 \ 18 \ 35 \ wy32dm1q.qyt
    返回:2012\08\27\18\35\wy32dm1q.qyt

  2. d:\溫度\ X \ Y \ 2012 \ 08 \ 27 \ 18 \ 36 \ tx84uwvr.puq
    返回:2012\08\27\18\36\tx84uwvr.puq

眼下我在2012年抓取了LastIndexOf(Path.DirectorySeparatorChar) N次以獲取字符串的索引,然後從該索引獲取子字符串。但是,我有一種感覺,也許有更好的辦法?

+0

我撤回我的答案,我只是注意到在你的問題中「超越」。我會寫一個匹配正則表達式「\\\ d {4} \\」的函數,將以下10個字符轉換爲DateTime,然後與01-01-2012進行比較。不幸的是,我缺乏正則表達式的專業知識,無法提供權威的答案。 –

+0

你有這個基目錄作爲你的應用程序中的變量嗎? –

+0

你也可以使用正則表達式,但爲什麼?將LastIndexOf打在for循環中,也許將它包裝在自己的方法中是很好的。 –

回答

3

這是一個使用正則表達式的解決方案,假設你正在尋找的格式總是包含\ YYYY \ MM \ DD \ HH \毫米。

class Program 
{ 
    static void Main(string[] args) 
    { 
     Console.WriteLine(ExtractPath(@"C:\Temp\X\2012\08\27\18\35\wy32dm1q.qyt")); 
     Console.WriteLine(ExtractPath(@"D:\Temp\X\Y\2012\08\27\18\36\tx84uwvr.puq")); 
    } 

    static string ExtractPath(string fullPath) 
    { 
     string regexconvention = String.Format(@"\d{{4}}\u{0:X4}(\d{{2}}\u{0:X4}){{4}}\w{{8}}.\w{{3}}", Convert.ToInt32(Path.DirectorySeparatorChar, CultureInfo.InvariantCulture)); 

     return Regex.Match(fullPath, regexconvention).Value; 
    } 
} 
+1

我喜歡Regex的想法,但它會返回前面的初始反斜槓。任何它不能返回的方式,所以我可以在Path.Combine中正確使用它?當然是 – michael

+0

!我更新了我的答案,所以它沒有前導斜槓:) –

+1

正則表達式應該使用'Path.DirectorySeparatorChar'來組成,因爲OP使用它(並且因爲它是在使用文件路徑時執行操作的正確方法)。 –

0

一個C#的解決辦法是

string str = @"C:\Temp\X\2012\08\27\18\35\wy32dm1q.qyt"; 
string[] arr=str.Substring(str.IndexOf("2012")).Split(new char[]{'\\'}); 
4
static void Main(string[] args) 
    { 
     Console.WriteLine(GetLastParts(@"D:\Temp\X\Y\2012\08\27\18\36\tx84uwvr.puq", @"\", 6)); 
     Console.ReadLine(); 
    } 

    static string GetLastParts(string text, string separator, int count) 
    { 
     string[] parts = text.Split(new string[] { separator }, StringSplitOptions.None); 
     return string.Join(separator, parts.Skip(parts.Count() - count).Take(count).ToArray()); 
    } 
+3

'Take'沒用。跳過'parts.Length - count'零件後,只剩下* count *個零件。 –

0

我不認爲你的現行方法有什麼問題。這可能是最好的工作。

public string GetFilepath(int nth, string needle, string haystack) { 
    int lastindex = haystack.Length; 

    for (int i=nth; i>=0; i--) 
     lastindex = haystack.LastIndexOf(needle, lastindex-1); 

    return haystack.Substring(lastindex); 
} 

我會保持簡單(KISS)。更容易調試/維護,可能是正則表達式的兩倍。