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,917
  • 1
  • 20
  • 26

5 Answers5

5
static bool Like(string expression, string value)
{
    return Regex.IsMatch(value, "^" + 
        Regex.Escape(expression).Replace("%", @"[\s\S]*?") + "$", 
        RegexOptions.IgnoreCase);
}
Rubens Farias
  • 55,782
  • 8
  • 132
  • 160
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,188
  • 2
  • 23
  • 27
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
  • 106,895
  • 9
  • 141
  • 243
0

You could realize that using regular expressions.

Please have a look at:

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

dknaack
  • 58,548
  • 26
  • 144
  • 194
0

what about using regex .*m.*

Mubashir Khan
  • 1,454
  • 12
  • 17