通过比较目录路径的一部分来匹配子目录

时间:2012-09-07 07:53:29

标签: c# .net regex string

我可能没有把标题说得太好,但希望我的解释能够说明问题。

基本上,当给定另一个要比较的路径时,我必须找出除了文件名之外的子目录的名称。例如,

Given: "C:\Windows\System32\catroot\sys.dll"

Compare: "C:\Windows"

Matched String: "\System32\catroot"

这是另一个例子:

Given: "C:\Windows\System32\WindowsPowerShell\v1.0\Examples\profile.ps1"

Compare: "C:\Windows\System32"

Matched String: "\WindowsPowerShell\v1.0\Examples"

执行此匹配的最佳方法是什么?

2 个答案:

答案 0 :(得分:4)

您可能还想考虑特殊情况,例如:

  • 相对路径

  • 短名称的路径,例如C:\PROGRA~1的{​​{1}}

  • 非规范路径(C:\Program Files

  • 使用备用分隔符的路径(C:\Windows\System32\..\..\file.dat代替/

一种方法是在比较之前使用\转换为规范的完整路径

E.g。

Path.GetFullPath

答案 1 :(得分:0)

无需使用正则表达式 可以使用string.StartsWithstring.SubstringPath.GetDirectoryName轻松完成此操作,以删除文件名。

string fullPath = @"C:\Windows\System32\WindowsPowerShell\v1.0\Examples\profile.ps1"; 
string toMatch = @"C:\Windows\System32";
string result = string.Empty;
if(fullPath.StartsWith(toMatch, StringComparison.CurrentCultureIgnoreCase) == true)
{
    result = Path.GetDirectoryName(fullPath.Substring(toMatch.Length));
} 
Console.WriteLine(result);
编辑:这种变化会照顾来自aiodintsov的观察结果,并包含@Joe关于非规范或部分路径名称的想法

string fullPath = @"C:\Windows\System32\WindowsPowerShell\v1.0\Examples\profile.ps1"; 
string toMatch = @"C:\Win";

string result = string.Empty;
string temp = Path.GetDirectoryName(Path.GetFullPath(fullPath));
string[] p1 = temp.Split('\\');
string[] p2 = Path.GetFullPath(toMatch).Split('\\');
for(int x = 0; x < p1.Length; x++)
{
   if(x >= p2.Length || p1[x] != p2[x]) 
             result = string.Concat(result, "\\", p1[x]);
}

在这种情况下,我假设部分匹配应被视为不匹配。 另请查看@Joe对部分或非规范路径问题的回答