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

时间:2008-10-21 19:30:20

标签: c# .net regex

如何使用C#中的正则表达式从完整路径中提取文件名?

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

如何使用正则表达式的.NET风格获取CoolFile.txt?我对正则表达式并不是很擅长,而我的RegEx伙伴和我无法想出这个。

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

6 个答案:

答案 0 :(得分:36)

为什么必须使用正则表达式? .NET具有专门用于此的内置Path.GetFileName()方法,适用于平台和文件系统。

答案 1 :(得分:19)

//  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
    );

更新:删除了开头斜杠

答案 2 :(得分:7)

这是一种方法:

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

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

答案 3 :(得分: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);

答案 4 :(得分:1)

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

显然需要扩展以覆盖所有路径字符,但命名组“file”包含给定示例路径的文件名。

答案 5 :(得分:0)

您应该使用System.Path类。这意味着如果你决定支持Mono / Linux,你将不得不担心(dlamblin的例子考虑了路径分离器,但是你可能得到一个奇怪的路径的奇怪操作系统)。 System.Path类还可以将两个路径合并为一个。例如:

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

将解决:

  • Windows:C:\ Documents and Settings \ [User] \ My Documents \ My App Stuff
  • Linux:/ [用户] /我的应用程序资料