C# find exact-match in string

david picture david · Nov 9, 2010 · Viewed 42.3k times · Source

How can I search for an exact match in a string? For example, If I had a string with this text:

label
label:
labels

And I search for label, I only want to get the first match, not the other two. I tried the Contains and IndexOf method, but they also give me the 2nd and 3rd matches.

Answer

Liviu Mandras picture Liviu Mandras · Nov 9, 2010

You can use a regular expression like this:

bool contains = Regex.IsMatch("Hello1 Hello2", @"(^|\s)Hello(\s|$)"); // yields false
bool contains = Regex.IsMatch("Hello1 Hello", @"(^|\s)Hello(\s|$)"); // yields true

The \b is a word boundary check, and used like above it will be able to match whole words only.

I think the regex version should be faster than Linq.

Reference