15

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.

david
  • 357
  • 2
  • 7
  • 18

4 Answers4

29

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

J. Scott Elblein
  • 4,013
  • 15
  • 58
  • 94
Liviu Mandras
  • 6,540
  • 2
  • 41
  • 65
  • For some reason, this did not work. It always yielded true no matter what I wrote. – david Nov 09 '10 at 10:27
  • You must have done something wrong because I checked it and it works perfectly. Maybe you could post the code that you say it always returns true. – Liviu Mandras Nov 09 '10 at 11:03
  • Ok, so apparently string reg = (@"\bHello\b"); works but string reg = (@"\b" + label + @"\b"); does not. Why is that and how can I fix it? – david Nov 09 '10 at 11:34
  • Ok, so apparently I have realised that the following code does not consider the colon, so true will still be returned even if I write Hello: – david Nov 09 '10 at 12:13
  • Try this: reg = ("\\b"+label+"\\b"); without the "@" – Liviu Mandras Nov 09 '10 at 12:39
  • Still doesn't fix it. Like I said, the regex is ignoring the colon. :\ – david Nov 09 '10 at 13:45
  • Take a look at this question: http://stackoverflow.com/questions/4134605/regex-and-the-colon – Liviu Mandras Nov 09 '10 at 14:24
3

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", " ");
Sergii Zhevzhyk
  • 4,074
  • 22
  • 28
g.geloso
  • 159
  • 1
  • 12
1

You could try a LINQ version:

string str = "Hello1 Hello Hello2";
string another = "Hello";
string retVal = str.Split(" \n\r".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
                   .First( p => p .Equals(another));
Sergii Zhevzhyk
  • 4,074
  • 22
  • 28
Saeed Amiri
  • 22,252
  • 5
  • 45
  • 83
1

It seems you've got a delimiter (crlf) between the words, so you could include the delimiter as part of the search string.

If not then I'd go with Liviu's suggestion.

J. Scott Elblein
  • 4,013
  • 15
  • 58
  • 94
Shiv Kumar
  • 9,599
  • 2
  • 36
  • 38