Parse filename from full path using regular expressions in C#


Question

How do I pull out the filename from a full path using regular expressions in C#?

Say I have the full path C:\CoolDirectory\CoolSubdirectory\CoolFile.txt.

How do I get out CoolFile.txt using the .NET flavor of regular expressions? I'm not really good with regular expressions, and my RegEx buddy and me couldn't figure this one out.

Also, in the course of trying to solve this problem, I realized that I can just use System.IO.Path.GetFileName, but the fact that I couldn't figure out the regular expression is just making me unhappy and it's going to bother me until I know what the answer is.

1
19
3/8/2010 1:56:44 PM

Accepted Answer

//  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: removed beginning slash

19
10/21/2008 8:18:42 PM

Why must you use regular expressions? .NET has the built-in Path.GetFileName() method specifically for this which works across platforms and filesystems.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon