Is there any way to search patterns in strings in C#?
Something like Sql LIKE would be very useful.
Regular expressions allow for everything that LIKE
allows for, and much more, but have a completely different syntax. However, since the rules for LIKE
are so simple(where %
means zero-or-more characters and _
means one character), and both LIKE
arguments and regular expressions are expressed in strings, we can create a regular expression that takes a LIKE
argument (e.g. abc_ef% *usd
) and turn it into the equivalent regular expression (e.g. \Aabc.ef.* \*usd\z
):
@"\A" + new Regex(@"\.|\$|\^|\{|\[|\(|\||\)|\*|\+|\?|\\").Replace(toFind, ch => @"\" + ch).Replace('_', '.').Replace("%", ".*") + @"\z"
From that we can build a Like()
method:
public static class MyStringExtensions { public static bool Like(this string toSearch, string toFind) { return new Regex(@"\A" + new Regex(@"\.|\$|\^|\{|\[|\(|\||\)|\*|\+|\?|\\").Replace(toFind, ch => @"\" + ch).Replace('_', '.').Replace("%", ".*") + @"\z", RegexOptions.Singleline).IsMatch(toSearch); } }
And hence:
bool willBeTrue = "abcdefg".Like("abcd_fg"); bool willAlsoBeTrue = "abcdefg".Like("ab%f%"); bool willBeFalse = "abcdefghi".Like("abcd_fg");
There are couple of ways you can search as "LIKE" operator of SQL in C#. If you just want to know whether the pattern exists in the string variable, you can use
string value = "samplevalue"; value.Contains("eva"); // like '%eva%' value.StartsWith("eva"); // like 'eva%' value.EndsWith("eva"); // like '%eva'
if you want to search the pattern from a list of string, you should use LINQ to Object Features.
List<string> valuee = new List<string> { "samplevalue1", "samplevalue2", "samplevalue3" }; List<string> contains = (List<string>) (from val in valuee where val.Contains("pattern") select val); // like '%pattern%' List<string> starts = (List<string>) (from val in valuee where val.StartsWith("pattern") select val);// like 'pattern%' List<string> ends = (List<string>) (from val in valuee where val.EndsWith ("pattern") select val);// like '%pattern'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With