Thursday, May 21, 2015

Using regex inside LINQ

When using .Contains with LINQ, there can sometimes be some false positives with the results. For example the word "concatenate" would return for .contains of the string "cat". This may not be iddeal, so regex can be used in LINQ to provide more relevant results.
var testList = new [] {"You may concatenate a string.", "They have a cat.", "Cat is a feline.", "Her name is Catherine."};
var regex = new Regex(@"(^|\W)cat", RegexOptions.IgnoreCase | RegexOptions.Multiline);

var matches = testList.Where (l => rexex.IsMatch(l));
In the example above the regex is going to match for inputs that begin with the word "cat" or contain a word beginning with cat. So "You may concatenate a string." would not pass, because cat is not at the start of the word. However the other 3 examples would because the word cat is there or a word that begins with it.

No comments:

Post a Comment