Regex相關知識,參考MSDN文檔:http://msdn.microsoft.com/zh-cn/library/az24scfc.aspx 和 http://msdn.microsoft.com/zh-cn/library/63ew9az0.aspxclass Program
{
static void Main(string[] args)
{
Regex reg = new Regex(@"^(?<fpath>([a-zA-Z]:\\)([\s\.\-\w]+\\)*)(?<fname>[\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
{
/// <summary>
/// 路徑分類
/// </summary>
public enum RouteType
{
/// <summary>
/// 僅檔案名稱
/// </summary>
NameOnly = 0,
/// <summary>
/// 檔案名稱(包括尾碼)
/// </summary>
FileName = 1,
/// <summary>
/// 僅尾碼名(包括.)
/// </summary>
FileSuffix = 2,
/// <summary>
/// 除檔案名稱之外的路徑
/// </summary>
PathExceptName = 3,
/// <summary>
/// 除尾碼之外的路徑
/// </summary>
PathExceptSuffix = 4
}
/// <summary>
/// 程式入口函數
/// </summary>
/// <param name="args"></param>
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();
}
/// <summary>
/// 正則擷取檔案路徑
/// </summary>
/// <param name="strRoute">完整檔案名稱</param>
/// <param name="rType">要擷取路徑類型</param>
/// <returns></returns>
public static string GetPartRoute(string strRoute, RouteType rType)
{
string strResult = string.Empty;
Regex regex = new Regex(@"^(?<fpath>([a-zA-Z]:\\)([\s\.\-\w]+\\)*)(?<fname>[\w]+)(?<namext>(\.[\w]+)*)(?<suffix>\.[\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;
}
}
}
點此下載