对于每场比赛,期待下一个“\”字符。所以你可能会得到“c:\mydir\”。检查该目录是否存在。然后找到下一个\
,给出“c:\mydir\subdir`。检查那个路径。最终你会找到一个不存在的路径,或者你会进入下一个匹配的开始。
那时,您知道要查找的目录。然后只需调用Directory.GetFiles
并匹配与从您找到的最后一个路径开始的子字符串匹配的最长文件名。
这应该最大限度地减少回溯。
这是如何做到的:
static void FindFilenamesInMessage(string message) {
// Find all the "letter colon backslash", indicating filenames.
var matches = Regex.Matches(message, @"\w:\\", RegexOptions.Compiled);
// Go backwards. Useful if you need to replace stuff in the message
foreach (var idx in matches.Cast<Match>().Select(m => m.idx).Reverse()) {
int length = 3;
var potentialPath = message.Substring(idx, length);
var lastGoodPath = potentialPath;
// Eat "\" until we get an invalid path
while (Directory.Exists(potentialPath)) {
lastGoodPath = potentialPath;
while (idx+length < message.Length && message[idx+length] != '\\')
length++;
length++; // Include the trailing backslash
if (idx + length >= message.Length)
length = (message.Length - idx) - 1;
potentialPath = message.Substring(idx, length);
}
potentialPath = message.Substring(idx);
// Iterate over the files in directory we found until we get a match
foreach (var file in Directory.EnumerateFiles(lastGoodPath)
.OrderByDescending(s => s.Length)) {
if (!potentialPath.StartsWith(file))
continue;
// 'file' contains a valid file name
break;
}
}
}