Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse filename from full path using regular expressions in C#

Tags:

c#

.net

regex

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.

like image 884
Jonathan Beerhalter Avatar asked Oct 21 '08 19:10

Jonathan Beerhalter


4 Answers

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

like image 156
Dour High Arch Avatar answered Nov 06 '22 01:11

Dour High Arch


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

like image 22
bdukes Avatar answered Nov 06 '22 00:11

bdukes


Here's one approach:

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

Basically, it matches everything between the very last backslash and the end of the string. Of course, as you mentioned, using Path.GetFileName() is much easier and will handle lots of edge cases that are a pain to handle with regex.

like image 7
Seth Petry-Johnson Avatar answered Nov 06 '22 01:11

Seth Petry-Johnson


Shorter:

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

Or:

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

Without Regex:

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

The official library support you mentioned:

string file = System.IO.Path.GetFileName(fullpath);
like image 7
dlamblin Avatar answered Nov 06 '22 01:11

dlamblin