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.
Why must you use regular expressions? .NET has the built-in Path.GetFileName()
method specifically for this which works across platforms and filesystems.
// 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
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With