如何列出句子中所有选中的关键字?

How to list all checked keywords from sentence?

这就是我所做的。

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

string sentence = Console.ReadLine();

int sentenceLength = sentence.Length;

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

if (matching.Success)
{
    Console.WriteLine(matching);  
}
else {
    Console.WriteLine("Keyword not found!");
}

但是如果句子中的每一个关键词都匹配,我想把它们都列出来。 使用上面的代码,控制台只写第一个匹配的词。

我必须使用 foreach 吗?但是怎么办?

例如:
关键字 = {"want", "buy", "will", "sell"};
句子 = "I want to buy some food."

那么结果:
想要,买

根据这个问题,我假设您正在寻找一个场景,您想要搜索列表 (keywords1) 中所有项目的输入文本 (sentence),如果是的话以下代码段将帮助您完成任务

List<string> keywords1 = new List<string>() { "word1", "word2", "word3", "word4" };
string sentence = Console.ReadLine(); //Let this be "I have word1, searching for word3"
Console.WriteLine("Matching words:");
bool isFound = false;
foreach (string word in keywords1.Where(x => sentence.IndexOf(x, StringComparison.OrdinalIgnoreCase) >= 0))
{
    Console.WriteLine(word);
    isFound = true;
}      
if(!isFound)
    Console.WriteLine("No Result");

示例输出:

input  : "I have word1, searching for word3"
output : Matching words:
word1
word3

在我看来,这将是最简单的:

var keyword = new [] {"want", "buy", "will", "sell"};
var sentence = "I want to buy some food." ;

var matches = keyword.Where(k => sentence.Contains(k));

Console.WriteLine(String.Join(", ", matches));

这导致:

want, buy

或者更强大的版本是:

var matches = Regex.Split(sentence, "\b").Intersect(keyword);

这仍然会产生相同的输出,但是如果 "swill""seller" 出现在 sentence.

中,则会避免匹配单词 "swill""seller"