我有一个文本列,其中包含来自 PDF、word、excel 等的纯文本。使用 SQL 搜索短语效果很好。
用户希望在打开文件之前查看包含搜索短语的文本摘录。由于 SQL 不返回短语在列中的位置,我决定使用正则表达式来查找和显示它。
当文本很大 27 MB 时,CPU 会跳到接近 100% 并且执行速度很慢。正则表达式模式检索搜索词前后的 5 个词。
代码如下:
HashSet<string> str = new HashSet<string>();
foreach (string sPhrase in searchArr)
{
string sPattern;
if (sPhrase.Contains("*"))
sPattern = sPhrase.Replace("*", @"\w*");
else
sPattern = sPhrase;
string pattern = "(?:[a-zA-Z'-]+[^a-zA-Z'-]+){0,5}" + sPattern + "(?:[^a-zA-Z'-]+[a-zA-Z'-]+){0,5}";
Debug.Write(string.Format("Pattern:{0}\n\r",pattern));
Regex reg = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
Match match = reg.Match(Text);
while (!String.IsNullOrEmpty(match.Value))
{
string s = match.Value;
if (s.Contains("\n\r"))
s = s.Replace("\n\r", " ");
s = s.Replace("\n", " ");
s = s.Replace("\r", " ");
//Checks for dups
if (!str.Contains(s))
{
str.Add(s);
AttachmentSearchResult r = new AttachmentSearchResult(s);
yield return r;
}
match = match.NextMatch();
}
}
我做错了什么?除了检索内存中的所有文本并进行搜索之外,还有更好的方法吗?或者 SQL 2005 可以完成我想要做的事情吗? 谢谢
请您参考如下方法:
我能想到的唯一方法是使用专用搜索引擎。我用过 Lucene.NET之前做过类似的东西,比较直接。您可能还想查看 SimpleLucene让您的生活更轻松。
但是,添加一个全新的搜索引擎将需要时间投入,这可能是不可行的。
