我有一个案例,我有一系列关键字。我想在给定的字符串中找到它们的匹配,并在每个字符串之前和之后返回x个字。
我可以编写一个循环引擎,它通过每个数组,返回一个给定的索引,并根据这些循环执行连接的子字符串,但这似乎有点冗长。
我听说过Lucene,但不确定实现整个框架是否值得。另外,如果可能的话,我怎么能用Lucene完成?
感谢。
答案 0 :(得分:2)
也许正则表达式会有所帮助...... 这将构建一个匹配字符串列表(最多3个字之前)关键字(最多3个字)
编辑:我错过了几个0和一些@s。再试一次。
private static void GetMatches (string s)
{
string[] keywords = {"if", "while", "do"};
int x = 3; // words before and after
string ex =
@"(\w+\W+){0," + x + @"}\b(" + string.Join("|", keywords) + @")\b\W+(\w+\W+){0," + x + @"}";
Regex regex = new Regex(ex);
List<string> matches = new List<string>();
foreach (Match match in regex.Matches (s))
{
matches.Add(match.Value);
}
}