c# Whole Word Matching (RegEx)

metal-detector-shmarkiiIf 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) {

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) {

Of course, this is just a tiny portion of the power of Regex. Happy matching!

c# Whole Word Matching (RegEx)

2 thoughts on “c# Whole Word Matching (RegEx)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s