2013-06-03 44 views
2

的模式,我需要了解各個項目的子串在文件路徑的列表。我正在循環的列表在文件系統中不存在,所以我不能使用Path類。我想從字符串的末尾開始解析,並在到達第一個「/」後停止。我嘗試過.Substring()和.Split(),但這兩種方法似乎都無法匹配指定的模式或從右向左讀取。如何解析字符串匹配在C#

例如:有的目錄/子目錄的一些/ SomeFile.pdf的

我想捕捉 「SomeFile.pdf的」

回答

0
Path.GetFileName(path) 

使用Path類是最簡單,最正確的和安全的方式。但是,如果要從字符串的末尾或從右向左解析,則有一種方法是反轉字符串並對其進行解析。

反轉字符串,搜索「/」,得到串,扭轉你的子,你有什麼,你所期待的。

舉例:你的路徑調用方法GetFileNameFromPath,它將打印SomeFile.pdf的。

using System; 
public class Test 
{ 
    public static void Main() 
    { 
     string path = "Some Directory/Some SubDirectory/SomeFile.pdf"; 
     string fileName = GetFileNameFromPath(path); 
     Console.WriteLine(fileName); 
    } 
    public static string GetFileNameFromPath(string path) 
    { 
     string fileName = string.Empty; 
     path = path.ReverseString(); 
     fileName = path.Substring(0, path.IndexOf(@"/")); 
     fileName = fileName.ReverseString(); 
     return fileName; 
    } 
} 

public static class StringExtension 
{ 
    public static string ReverseString(this string s) 
    { 
     char[] arr = s.ToCharArray(); 
     Array.Reverse(arr); 
     return new string(arr); 
    } 
} 
+0

如果你打算這樣做,使用linq並做'path.Split('/')。Last()'? –

+0

爲什麼你嘗試實施低效'GetFileNameFromFullPath'如果已經有一個['Path.GetFileName'(http://msdn.microsoft.com/en-us/library/system.io.path.getfilename(V = vs.71).aspx)從.NET 1.1開箱即用? –

+0

是的,它會更容易,我只是複製了一些關於此主題的舊代碼。由於該問題沒有說明.NET框架版本,所以提出LINQ會更容易。 – jmelhus

10

您應該使用Path類代替。

例如:

string path = "Some Directory/Some SubDirectory/SomeFile.pdf"; 
string fileName = System.IO.Path.GetFileName(path); 

Demo

編輯:剛纔回答你原來的問題如何 「從右至左讀」:

您可以使用String.SubstringString.LastIndexOf

string fileName = path.Substring(path.LastIndexOf("/") + 1); 

Demo

(但是,使用Path類,如果你有路徑工作)

+0

1爲ideone.com – Jason

+1

路徑是唯一最利用不足的類在.NET。每個人都認爲他們應該自己做這種解析。 – Cemafor

+2

@Cema我很久沒有了解Path.Combine。不過,我希望我做到了。 –

0

使用Path是最好的,如果你實際上是把它當作文件/文件夾的信息,但如果你把它當作一個字符串,你恰好想在「/」,那麼你可能分裂然後反向拆分:

string str = "Some Directory/Some SubDirectory/SomeFile.pdf"; 
string[] terms = str.Split('/'); 
Array.Reverse(terms); 
foreach (string term in terms) 
{ 
    Console.WriteLine(term); 
} 
+0

此打印: 'SomeFile.pdf' '有些SubDirectory' '有些Directory' 不是有什麼要求。 –

+0

對不起,是的。我誤解了這一點:「我需要爲文件路徑列表中的每個項目捕獲一個子字符串。」 (此外,使用PathSeparator同樣簡單。) –