String compare C# – whole word match

The simplest solution is to use regular expressions and the word boundary delimiter \b:

bool result = Regex.IsMatch(text, "\\bthe\\b");

or, if you want to find mismatching capitalisation,

bool result = Regex.IsMatch(text, "\\bthe\\b", RegexOptions.IgnoreCase);

(using System.Text.RegularExpressons.)

Alternatively, you can split your text into individual words and search the resulting array. However, this isn’t always trivial because it’s not enough to split on white spaces; this would ignore all punctuation and yield wrong results. A solution is to once again use regular expressions, namely Regex.Split.

Leave a Comment