如果您只需要检查子字符串,则可以使用简单的 LINQ 查询:
var q = words.Any(w => myText.Contains(w));
// returns true if myText == "This password1 is weak";
如果要检查整个单词,可以使用正则表达式:
匹配作为所有单词析取的正则表达式:
// 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);
使用正则表达式将字符串拆分为单词,并测试单词集合的成员资格(如果您使用 make words into aHashSet
而不是 a ,这将变得更快List
):
var pattern = new Regex(@"\W");
var q = pattern.Split(myText).Any(w => words.Contains(w));
为了根据此标准过滤句子集合,您只需将其放入函数中并调用Where
:
// Given:
// bool HasThoseWords(string sentence) { blah }
var q = sentences.Where(HasThoseWords);
或者把它放在一个 lambda 中:
var q = sentences.Where(s => Regex.Split(myText, @"\W").Any(w => words.Contains(w)));
Ans From =>如何检查我的 List<string> 中的任何单词是否包含在@R 的文本中。马蒂尼奥费尔南德斯