如何使用C#中的正则表达式从完整路径中提取文件名?
说我有完整的路径C:\CoolDirectory\CoolSubdirectory\CoolFile.txt.
如何使用正则表达式的.NET风格获取CoolFile.txt?我对正则表达式并不是很好,而且我的RegEx伙伴和我无法想出这个.
此外,在尝试解决这个问题的过程中,我意识到我可以使用 System.IO.Path.GetFileName,但事实上我无法弄清楚正则表达式只是让我不开心,它会打扰我,直到我知道答案是什么是.
Dou*_*rch 36
为什么必须使用正则表达式?.NET具有Path.GetFileName()专门针对此的内置方法,可以跨平台和文件系统工作.
bdu*_*kes 19
// 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
);
Run Code Online (Sandbox Code Playgroud)
更新:删除开始斜杠
这是一种方法:
string filename = Regex.Match(filename, @".*\\([^\\]+$)").Groups[1].Value;
Run Code Online (Sandbox Code Playgroud)
基本上,它匹配最后一个反斜杠和字符串结尾之间的所有内容.当然,正如您所提到的,使用Path.GetFileName()更容易,并且将处理许多边缘情况,这些情况很难处理正则表达式.
更短:
string filename = Regex.Match(fullpath, @"[^\\]*$").Value;
Run Code Online (Sandbox Code Playgroud)
要么:
string filename = Regex.Match(fullpath, "[^\\"+System.IO.Path.PathSeparator+"]*$").Value;
Run Code Online (Sandbox Code Playgroud)
没有Regex:
string[] pathparts = fullpath.Split(new []{System.IO.Path.PathSeparator});
string file = pathparts[pathparts.Length-1];
Run Code Online (Sandbox Code Playgroud)
您提到的官方图书馆支持:
string file = System.IO.Path.GetFileName(fullpath);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
43538 次 |
| 最近记录: |