Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# find exact-match in string

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.

like image 353
david Avatar asked Nov 09 '10 07:11

david


2 Answers

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

like image 169
Liviu Mandras Avatar answered Sep 21 '22 19:09

Liviu Mandras


You can try to split the string (in this case the right separator can be the space but it depends by the case) and after you can use the equals method to see if there's the match e.g.:

private Boolean findString(String baseString,String strinfToFind, String separator)
{                
    foreach (String str in baseString.Split(separator.ToCharArray()))
    {
        if(str.Equals(strinfToFind))
        {
            return true;
        }
    }
    return false;
}

And the use can be

findString("Label label Labels:", "label", " ");
like image 29
g.geloso Avatar answered Sep 21 '22 19:09

g.geloso