If you’ve ever wanted to test a string to see if a word exists, but can’t use “.contains” because it doesn’t respect whole words (not that I would expect it to), below is a fast, simple way using Regex:
Of course you’ll need: using System.Text.RegularExpressions;
Now setup your pattern and Regex object:
string pattern = @"\bteam\b"; Regex rx = new Regex(pattern, RegexOptions.IgnoreCase);
Now create a match:
Match m = rx.Match("Teamwork is working together.");
Does the word exist:
if (m.Success) { //no }
Try again using a string with the whole word:
Match m = rx.Match("I am just part of the team.");
Does the word exist now?:
if (m.Success) { //yes! }
Of course, this is just a tiny portion of the power of Regex. Happy matching!
Why downvote without any comments?
LikeLike
Good question!
LikeLiked by 1 person
it doesn’t work for me in c#2010. do u have an idea?
LikeLike
What error do you receive?
LikeLike