這裏是一個會做完全相同的代碼,你期待什麼:
public static string GetSubdirectoryFromPath(string path, string parentDirectory, bool ignoreCase = true)
{
// 1. Standarize the path separators.
string safePath = path.Replace("/", @"\");
string safeParentDirectory = parentDirectory.Replace("/", @"\").TrimEnd('\\');
// 2. Prepare parentDirectory to use in Regex.
string directory = Regex.Escape(safeParentDirectory);
// 3. Find the immediate subdirectory to parentDirectory.
Regex match = new Regex(@"(?:|.+)" + directory + @"\\([^\\]+)(?:|.+)", ignoreCase ? RegexOptions.IgnoreCase : RegexOptions.None);
// 4. Return the match. If not found, it returns null.
string subDirectory = match.Match(safePath).Groups[1].ToString();
return subDirectory == "" ? null : subDirectory;
}
的測試代碼:
void Test()
{
string path1 = @"C:\Code\Dev\Branches\Latest\bin\abc.dll";
string path2 = @"C:\Dev\Branches\5.1";
string path3 = @"D:\My Documents\Branches\7.0\Source\test.cs";
Console.WriteLine("Matches:");
Console.WriteLine(GetSubdirectoryFromPath(path1, "dev/branches/") ?? "Not found");
Console.WriteLine(GetSubdirectoryFromPath(path1, @"Dev\Branches") ?? "Not found");
Console.WriteLine(GetSubdirectoryFromPath(path3, "D:/My Documents/Branches") ?? "Not found");
// Incorrect parent directory.
Console.WriteLine(GetSubdirectoryFromPath(path2, "My Documents") ?? "Not found");
// Case sensitive checks.
Console.WriteLine(GetSubdirectoryFromPath(path3, @"My Documents\Branches", false) ?? "Not found");
Console.WriteLine(GetSubdirectoryFromPath(path3, @"my Documents\Branches", false) ?? "Not found");
// Output:
//
// Matches:
// Latest
// Latest
// 7.0
// Not found
// 7.0
// Not found
}
你去將不得不m做出兩個假設之一。 「Branches」下方只有一個文件夾,或者您將按字母順序抓取第一個文件夾。這真的是你想要的嗎? – 2013-02-28 12:48:35
@MichaelPerrenoud我相信OP意味着給定路徑中的下一部分 – 2013-02-28 12:49:34
您不希望使用字符串查找函數來定位兩個斜線之間的字符串嗎? – roymustang86 2013-02-28 12:49:37