如何检查我的List <string>中的任何单词是否包含在文本中

Max*_*xim 16 c# linq

我有一个

List<string> words = new List<string> {"word1", "word2", "word3"};
Run Code Online (Sandbox Code Playgroud)

如果我的字符串包含任何这些单词,我想检查使用linq; Smthng喜欢:

var q = myText.ContainsAny(words);
Run Code Online (Sandbox Code Playgroud)

第二,如果我也有一个句子列表:

List<string> sentences = new List<string> { "sentence1 word1" , "sentence2 word2" , "sentence3 word3"};
Run Code Online (Sandbox Code Playgroud)

并且还要检查这些句子中是否包含任何这些单词!

 var q = sentences.Where(s=>words.Any(s.text))....
Run Code Online (Sandbox Code Playgroud)

R. *_*des 43

如果只需要检查子字符串,则可以使用简单的LINQ查询:

var q = words.Any(w => myText.Contains(w));
// returns true if myText == "This password1 is weak";
Run Code Online (Sandbox Code Playgroud)

如果要检查整个单词,可以使用正则表达式:

  1. 匹配正则表达式,这是所有单词的分离:

    // you may need to call ToArray if you're not on .NET 4
    var escapedWords = words.Select(w => @"\b" + Regex.Escape(w) + @"\b");
    // the following line builds a regex similar to: (word1)|(word2)|(word3)
    var pattern = new Regex("(" + string.Join(")|(", escapedWords) + ")");
    var q = pattern.IsMatch(myText);
    
    Run Code Online (Sandbox Code Playgroud)
  2. 将字符串拆分为带有正则表达式的单词,并测试单词集合的成员资格(如果您使用make words HashSet而不是a,这将变得更快List):

    var pattern = new Regex(@"\W");
    var q = pattern.Split(myText).Any(w => words.Contains(w));
    
    Run Code Online (Sandbox Code Playgroud)

为了根据这个标准过滤句子集合,你所要做的就是把它放到一个函数中并调用Where:

 // Given:
 // bool HasThoseWords(string sentence) { blah }
 var q = sentences.Where(HasThoseWords);
Run Code Online (Sandbox Code Playgroud)

或者把它放在lambda中:

 var q = sentences.Where(s => Regex.Split(myText, @"\W").Any(w => words.Contains(w)));
Run Code Online (Sandbox Code Playgroud)


And*_*ose 5

var q = words.Any(w => myText.Contains(w));
Run Code Online (Sandbox Code Playgroud)

要返回包含一个或多个单词的所有句子:

var t = sentences.Where(s => words.Any(w => s.Contains(w)));

            foreach (var sentence in t)
            {
                Console.WriteLine(sentence);
            }
Run Code Online (Sandbox Code Playgroud)