在C#中使用正则表达式解析来自全路径名 [英] Parse filename from full path using regular expressions in C#

查看:321
本文介绍了在C#中使用正则表达式解析来自全路径名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用在C#中的正则表达式的完整路径拔出名



说我有完整的路径 C:\\ \\CoolDirectory\CoolSubdirectory\CoolFile.txt



使用正则表达式的.NET味道怎样走出CoolFile.txt?我不使用正则表达式真的很不错,我的正则表达式的哥们和我想不出这一个。



此外,在试图解决这个问题的过程中,我意识到,我可以只使用 System.IO.Path.GetFileName ,但事实上,我无法弄清楚的正则表达式只是让我不开心,这是怎么回事打扰我,直到我知道答案是什么。


解决方案

  //使用系统。 Text.RegularExpressions; 

///<总结>
/// C#的基于正则表达式:星期二,2008年10月21日,下午二时34分30秒
///使用快报版本:3.0.2766,HTTP://www.ultrapico。 COM
///
///正则表达式的描述:
///
///任何字符,是不是在这个类:[\\ ],任何数量的重复
///线或字符串
///
///
///<结束; /总结>
公共静态正则表达式的regex ​​=新的正则表达式(
@[^ \\] * $,
RegexOptions.IgnoreCase
| RegexOptions.CultureInvariant
| RegexOptions .IgnorePatternWhitespace
| RegexOptions.Compiled
);



更新:删除开始斜杠


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.

解决方案

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

这篇关于在C#中使用正则表达式解析来自全路径名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆