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

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

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

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

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

 // using System.Text.RegularExpressions; ///  /// 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 /// /// ///  public static Regex regex = new Regex( @"[^\\]*$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled ); 

更新:删除开始斜杠

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

这是一种方法:

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

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

短:

 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); 
 \w+:\\(\w+\\)*(?\w*\.\w*) 

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

您应该使用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:/ [用户] /我的应用程序