Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Check a word exists in a string

Tags:

c#

regex

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

like image 428
Gavin Avatar asked Dec 19 '25 03:12

Gavin


2 Answers

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
}
like image 133
Lucero Avatar answered Dec 20 '25 15:12

Lucero


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.

like image 22
Jouni Heikniemi Avatar answered Dec 20 '25 17:12

Jouni Heikniemi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!