Search code examples
c#matchkeywordsentence

How to list all checked keywords from sentence?


This is what I did.

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!");
}

but if the sentence have every keyword match, I want to list them all. With the code above, the console just writes the first matching word.

Do I have to use foreach? But how?

For example:
keyword = {"want", "buy", "will", "sell"};
sentence = "I want to buy some food."

Then the result:
want, buy


Solution

  • It seems to me that this would be the easiest:

    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));
    

    This results in:

    want, buy
    

    Or a more robust version would be:

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

    This still produces the same output, but avoids matching on the word "swill" or "seller" if they occurred in the sentence.