我一直在尝试使用C#中的正则表达式捕获文件夹路径中的最后一个文件夹,但我对此非常陌生以解决这个问题。例如,如果我有C:\ Projects \ Test,那么表达式应返回Test。如果我有H:\ Programs \ Somefolder \ Someotherfolder \ Final那么结果应该是Final。我已经尝试了以下代码,但它只是爆炸了。谢谢你的帮助。
string pattern = ".*\\([^\\]+$)";
Match match = Regex.Match("H:\\Projects\\Final", pattern, RegexOptions.IgnoreCase);
答案 0 :(得分:5)
为什么使用正则表达式?您可以使用DirectoryInfo.Name
var directoryname = new DirectoryInfo(@"C:\Projects\Test").Name;
\\The variable directoryname will be Test
答案 1 :(得分:2)
也许这个?
string strRegex = @".*\\(.*)"; RegexOptions myRegexOptions = RegexOptions.IgnoreCase | RegexOptions.Multiline;
Regex myRegex = new Regex(strRegex, myRegexOptions);
string strTargetString = @"H:\Programs\Somefolder\Someotherfolder\Final";
string strReplace = @"$1";
return myRegex.Replace(strTargetString, strReplace);
答案 2 :(得分:2)
当你有一套非常完整的.NET库可以为你做这件事时,这是一个很糟糕的正则表达式...使用System.IO.Path或System.IO.DirectoryInfo下面的两个简单方法
string path = @"H:\Programs\Somefolder\Someotherfolder\Final";
Console.WriteLine(System.IO.Path.GetFileName(path));
Console.WriteLine(new System.IO.DirectoryInfo(path).Name);
答案 3 :(得分:1)
为什么不使用拆分?
string str =“c:\ temp \ temp1 \ temp2”;
string lastfolder = str.Split(“\”)。Last;