1

我想知道是否有办法检查字符串是否包含任何关键字是列表,如果找到则返回找到的关键字。

例如,我有一个keywords.

List<string> keywords = new List<string>{"word1", "word2", "word3"};

我有一个sentence(字符串)我想检查关键字:

string sentence = "something something something word2 something something";

keywords有没有办法在里面搜索sentence并返回找到的?例如,返回word2

我知道我可能只使用 forloop 来循环关键字,但由于在我的实际程序中至少有 20 个关键字,我不想这样做,因为它会使我的代码有点混乱。

我原来的想法是这样的:

string SearchKeywords(List<string> keywords, string sentence){
    foreach (string word in keywords){
        if (sentence.Contains(word)) return word;
    }
    return ""; //return blank string if no match found
}

我想知道是否有一个内置函数可以用来完成这项工作。谢谢!

4

3 回答 3

3

You could use Linq's FirstOrDefault extension method:

string SearchKeywords(List<string> keywords, string sentence){
    return keywords.FirstOrDefault(w => sentence.Contains(w)) ?? "";
}

The ?? "" at the end simply means that if no keyword is found within the string, your method should return an empty string.

于 2013-11-12T15:07:06.703 回答
3

使用正则表达式,您可以使用关键字创建一个交替来获得word1|word2|word3. 它们应该通过转义Regex.Escape以避免与任何正则表达式元字符冲突。忽略大小写是通过添加RegexOptions.IgnoreCase选项来完成的。

string pattern = String.Join("|", keywords.Select(k => Regex.Escape(k)));
Match m = Regex.Match(sentence, pattern, RegexOptions.IgnoreCase);

if (m.Success)
{
    Console.WriteLine("Keyword found: {0}", m.Value);
}
else
{
    Console.WriteLine("No keywords found!");
}

如果您改变主意并想查找多个匹配项,请Regex.Matches改用并循环遍历其结果。

于 2013-11-12T15:17:18.540 回答
0

If you know that you'll only get one word per sentence (and you're sure you're only checking one sentence at a time), I'd use p.s.w.g's answer. For a similar one which will look through a longer string (and thus possibly return multiple results) just use .Where() like this:

IEnumerable<string> SearchKeywords(List<string> keywords, string sentence)
{
  return keywords.Where(w => sentence.ToLower().Contains(w.ToLower()));
}

In this case, you don't need the null coalescing operator (??) because the Enumerable will be returned either way, if there aren't any matches, then it will return an Enumerable with no elements.

Note that this will find partial-word matches (for instance, keyword "cray" would match on sentence word "crayon." You can fix that by adding spaces around your keywords (thus: " cray "), or by splitting your sentence into an array with .Split() and check the two Enumerables against each other:

IEnumerable<string> SearchKeywords(List<string> keywords, string sentence)
{
  var splitSentence = sentence.ToLower().Split(' ');
  return keywords.Intersect(splitSentence);
}
于 2013-11-12T15:31:53.733 回答