2008-10-21 172 views
17

如何从C#中使用正则表达式的完整路径拉出文件名?从C#中使用正则表达式的完整路径解析文件名#

说我有完整路径C:\CoolDirectory\CoolSubdirectory\CoolFile.txt

如何使用正则表达式的.NET风格取出CoolFile.txt?我对正则表达式不太擅长,我的RegEx伙伴和我无法弄清楚这一点。

此外,在试图解决这个问题的过程中,我意识到我可以使用System.IO.Path.GetFileName,但我无法弄清楚正则表达式的事实只是让我不快乐,它会打扰我,直到我知道答案是什么。

+17

这很好,你想知道它将如何使用正则表达式,但为了让这个世界变得更美好,请保证你会使用Path。*无论如何:) – OregonGhost 2008-10-21 19:38:01

+0

GetFileName可能不是一个选项,如果你正在使用[长路径](http://bcl.codeplex.com/wikipage?title=Long%20Path) – 2012-06-09 22:40:05

+0

有理由和反对正则表达式:http: //www.codinghorror.com/blog/2008/06/regular-expressions-now-you-have-two-problems.html – benPearce 2012-07-09 00:29:02

回答

18
// using System.Text.RegularExpressions; 

/// <summary> 
/// Regular expression built for C# on: Tue, Oct 21, 2008, 02:34:30 PM 
/// Using Expresso Version: 3.0.2766, http://www.ultrapico.com 
/// 
/// A description of the regular expression: 
/// 
/// Any character that is NOT in this class: [\\], any number of repetitions 
/// End of line or string 
/// 
/// 
/// </summary> 
public static Regex regex = new Regex(
     @"[^\\]*$", 
    RegexOptions.IgnoreCase 
    | RegexOptions.CultureInvariant 
    | RegexOptions.IgnorePatternWhitespace 
    | RegexOptions.Compiled 
    ); 

UPDATE:删除开始斜杠

34

为什么你必须使用正则表达式? .NET专门为此提供了内置的Path.GetFileName()方法,可跨平台和文件系统使用。

+0

你没有仔细阅读过这个问题。他知道GetFileName(),但想知道如何使用reg ex来完成。 – Kon 2008-10-21 19:35:49

+4

当我发布我的答案时,那句话不在那里。 – 2008-10-21 19:37:33

6

这里有一个办法:

string filename = Regex.Match(filename, @".*\\([^\\]+$)").Groups[1].Value; 

基本上,它匹配的最后反斜线和字符串的结束之间的所有内容。当然,正如你所提到的,使用Path.GetFileName()更容易,并且会处理很多边界情况,这是一个很难用正则表达式处理的边界情况。

1
\w+:\\(\w+\\)*(?<file>\w*\.\w*) 

这显然需要扩大覆盖所有路径中的字符,但命名组“文件”包含您对于给出的示例路径文件名。

4

短:

string filename = Regex.Match(fullpath, @"[^\\]*$").Value; 

或者:

string filename = Regex.Match(fullpath, "[^\\"+System.IO.Path.PathSeparator+"]*$").Value; 

没有Regex:你提到

string[] pathparts = fullpath.Split(new []{System.IO.Path.PathSeparator}); 
string file = pathparts[pathparts.Length-1]; 

官方库支持:

string file = System.IO.Path.GetFileName(fullpath); 
0

您应该使用System.Path类。这意味着如果您决定支持Mono/Linux(dlamblin的示例将路径分隔符考虑在内,但您可能会得到一个具有奇怪路径的奇怪操作系统),您将不得不担心更少。 System.Path类还可以将两个路径合并为一个。因此,例如:

Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "My App Stuff"); 

将解析:

  • 的Windows:C:\ Documents和Settings \ [用户] \ My Documents \我应用的东西
  • 的Linux:/ [用户] /我的应用程序的东西