How do I pull out the filename from a full path using regular expressions in C#?
Say I have the full path
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.
// 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
Why must you use regular expressions? .NET has the built-in
Path.GetFileName() method specifically for this which works across platforms and filesystems.