C#正则表达式 匹配磁盘路径和文件名

2017-09-12 14:22:43来源:网络收集作者:管理员人点击

分享

正则表达式相关知识,参考MSDN文档:http://msdn.microsoft.com/zh-cn/library/az24scfc.aspx 和 http://msdn.microsoft.com/zh-cn/library/63ew9az0.aspx


class Program
{
static void Main(string[] args)
{
Regex reg = new Regex(@"^(?([a-zA-Z]://)([/s/./-/w]+//)*)(?[/w]+.[/w]+)");
Match result = reg.Match(@"D:/Program Files/AliWangWang/7.10.07C/emotions/TaoDoll/Sniffer.dat");
if (result.Success)
{
Console.WriteLine("[Full]:" + result.Value);
Console.WriteLine("[Part1]:" + result.Result("${fpath}"));
Console.WriteLine("[Part2]:" + result.Result("${fname}"));
}
Console.ReadLine();
}
}

简单整理如下,方便以后调用(支持多后缀名):


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Reflection;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
///
/// 路径分类
///

public enum RouteType
{
///
/// 仅文件名
///

NameOnly = 0,
///
/// 文件名(包括后缀)
///

FileName = 1,
///
/// 仅后缀名(包括.)
///

FileSuffix = 2,
///
/// 除文件名之外的路径
///

PathExceptName = 3,
///
/// 除后缀之外的路径
///

PathExceptSuffix = 4
}
///
/// 程序入口函数
///

///
static void Main(string[] args)
{
string strPath = @"D:/Program Files/Advanced PDF Password Recovery/Sniffer.dat.doc.bak.zip";
Console.WriteLine(GetPartRoute(strPath, RouteType.NameOnly));
Console.WriteLine(GetPartRoute(strPath, RouteType.FileName));
Console.WriteLine(GetPartRoute(strPath, RouteType.FileSuffix));
Console.WriteLine(GetPartRoute(strPath, RouteType.PathExceptName));
Console.WriteLine(GetPartRoute(strPath, RouteType.PathExceptSuffix));
Console.ReadLine();
}
///
/// 正则获取文件路径
///

/// 完整文件名
/// 要获取路径类型
///
public static string GetPartRoute(string strRoute, RouteType rType)
{
string strResult = string.Empty;
Regex regex = new Regex(@"^(?([a-zA-Z]://)([/s/./-/w]+//)*)(?[/w]+)(?(/.[/w]+)*)(?/.[/w]+)");
Match result = regex.Match(strRoute);
if (result.Success)
{
switch (rType)
{
case RouteType.NameOnly:
strResult = result.Result("${fname}") + result.Result("${namext}");break;
case RouteType.FileName:
strResult = result.Result("${fname}") + result.Result("${namext}") + result.Result("${suffix}"); break;
case RouteType.FileSuffix:
strResult = result.Result("${suffix}"); break;
case RouteType.PathExceptName:
strResult = result.Result("${fpath}"); break;
case RouteType.PathExceptSuffix:
strResult = result.Result("${fpath}") + result.Result("${fname}") + result.Result("${namext}"); break;
default:
strResult = strRoute; break;
}
}
return strResult;
}
}
}


最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台