tags:

views:

616

answers:

2

Is the best way to do this with Regex? I don't want it picking up partial words for example if I'm search for Gav it shouldn't match Gavin.

Any examples would be great as my regular expression skills are non existant.

Thanks

+15  A: 

Yes, a Regex is perfect for the job.

Something like:

string regexPattern = string.Format(@"\b{0}\b", Regex.Escape(yourWord));
if (Regex.IsMatch(yourString, regexPattern)) {
    // word found
}
Lucero
+1 for Regex.Escape()
RichieHindle
It's possible to add RegexOptions.IgnoreCase too, depending on whether or not the OP wants the match to be case-sensitive.
LukeH
+2  A: 

What you want is probably like this:

if (Regex.IsMatch(myString, @"\bGav\b")) { ... }

The \b:s in the regex indicate word boundaries, i.e. a whitespace or start/end of the string. You may also want to throw in RegexOptions.IgnoreCase as the third parameter if you want that. Note that the @-sign in front of the regex is essential, otherwise it gets misinterpreted due to the double meaning of the \ sign.

Jouni Heikniemi
It doesn't get misinterpreted, you just have to write the pattern differently: @"\bGav\b" is equal to "\\bGav\\b"
Lucero
Yes, exactly. However, I find the verbatim string literal (@"...")) to be far better for representing regular expressions, as Regex escape rules are complex enough as they are; throwing C# syntax into the mix just makes things harder, especially if you want to paste stuff into other environments where the escape rules rarely are the same.
Jouni Heikniemi