对于每个匹配,期待下一个'\'字符。所以你可能会得到“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;
}
}
}
听起来很明智! :-)今天晚些时候我会试一试,让你知道它的价格。 – joce
确实比较快!在55K消息的运行中,我的解决方案平均约50秒,而您的平均值大概为9秒!请记住,如果我通过实施您的解决方案来编辑您的文章? – joce
@Joce:去吧。 –