如何列出句子中所有已检查的关键字?

时间:2016-04-12 02:18:49

标签: c# match keyword 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吗?但是如何?

例如:
keyword = {“want”,“buy”,“will”,“sell”};
句子=“我想买些食物。”

然后结果:
想要,买

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

从问题我假设您正在寻找一个场景,您想要搜索列表中所有项目的输入文本(sentence)(keywords1),如果是这样,请关注片段将帮助您完成任务

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