C# find exact-match in string
Asked Answered
C

4

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.

Cynar answered 9/11, 2010 at 7:48 Comment(2)
why don't you just check str == "label"?Streamliner
he's looking for "whole word" search.. :)Patmore
M
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

Misinterpret answered 9/11, 2010 at 7:50 Comment(7)
For some reason, this did not work. It always yielded true no matter what I wrote.Cynar
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.Misinterpret
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?Cynar
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:Cynar
Try this: reg = ("\\b"+label+"\\b"); without the "@"Misinterpret
Still doesn't fix it. Like I said, the regex is ignoring the colon. :\Cynar
Take a look at this question: https://mcmap.net/q/822651/-regex-and-the-colonMisinterpret
S
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", " ");
Scag answered 9/11, 2010 at 8:39 Comment(0)
A
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));
Apotropaic answered 9/11, 2010 at 8:8 Comment(0)
C
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.

Compunction answered 9/11, 2010 at 10:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.