3

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".

Kai
  • 2,967
  • 1
  • 22
  • 28

5 Answers5

5
static bool Like(string expression, string value)
{
    return Regex.IsMatch(value, "^" + 
        Regex.Escape(expression).Replace("%", @"[\s\S]*?") + "$", 
        RegexOptions.IgnoreCase);
}
Rubens Farias
  • 57,174
  • 8
  • 131
  • 162
3
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.

robyaw
  • 2,274
  • 2
  • 22
  • 29
1

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('_', '.').

Community
  • 1
  • 1
Jon Hanna
  • 110,372
  • 10
  • 146
  • 251
0

You could realize that using regular expressions.

Please have a look at:

http://www.codeproject.com/KB/recipes/wildcardtoregex.aspx

dknaack
  • 60,192
  • 27
  • 155
  • 202
0

what about using regex .*m.*

Mubashir Khan
  • 1,464
  • 1
  • 12
  • 17