The accepted answer, and most others will present a logic failure when an unassociated word contains another. Such as "low" in "follow". Those are separate words and .Contains
and IndexOf
will fail on those.
Word Boundary
What is needed is to say that a word must stand alone and not be within another word. The only way to handle that situation is using regular expressions and provide a word boundary \b
rule to isolate each word properly.
Tests And Example
string first = "name";
var second = "low";
var sentance = "Follow your surname";
var ignorableWords = new List<string> { first, second };
The following are two tests culled from other answers (to show the failure) and then the suggested answer.
// To work, there must be *NO* words that match.
ignorableWords.Any(word => sentance.Contains(word)); // Returns True (wrong)
ignorableWords.Any(word => // Returns True (wrong)
sentance.IndexOf(word,
StringComparison.InvariantCultureIgnoreCase) >= 0);
// Only one that returns False
ignorableWords.Any(word =>
Regex.IsMatch(sentance, @$"\b{word}\b", RegexOptions.IgnoreCase));
Summary
.Any(word =>Regex.IsMatch(sentance, @$"\b{word}\b", RegexOptions.IgnoreCase)
- One to many words to check against.
- No internal word failures
- Case is ignored.