I am trying to write a c# search function that supports "%" in SQL like operator in searching. For eg,
"%m%" will match all strings like below.
- some
- me
- sum
- etc..
"%m%e" will match strings something like "some".
static bool Like(string expression, string value)
{
return Regex.IsMatch(value, "^" +
Regex.Escape(expression).Replace("%", @"[\s\S]*?") + "$",
RegexOptions.IgnoreCase);
}
public bool SqlWildcardMatch(string input, string sqlLikePattern)
{
sqlLikePattern = Regex.Replace(sqlLikePattern, "^([^%])", "^$1");
sqlLikePattern = Regex.Replace(sqlLikePattern, "([^%])$", "$1$$");
return Regex.IsMatch(input, string.Replace(sqlLikePattern, "%", ".*"));
}
This function will likely need refining to ensure sqlLikePattern
doesn't produce an invalid regex pattern, but consider it a starting point.
If you also want to have the way SQL's LIKE
treats underscores, you could use my answer to C# Version Of SQL LIKE and if not, you could remove the bit Replace('_', '.')
.
You could realize that using regular expressions.
Please have a look at: