String comparison with Wildcard search in c#

10,328

I suggest converting SQL-LIKE into regular expression:

private static string LikeToRegular(string value) {
  return "^" + Regex.Escape(value).Replace("_", ".").Replace("%", ".*") + "$";
}

And then use Regex as usual:

string like = "%A%C%";
string source = "A B C";

if (Regex.IsMatch(source, LikeToRegular(like))) {
  Console.Write("Matched");
}

You can even implement an extension method if you want:

public class StringExtensions {
  public static bool ContainsLike(this string source, string like) {
    if (string.IsNullOrEmpty(source))
      return false; // or throw exception if source == null
    else if (string.IsNullOrEmpty(like))
      return false; // or throw exception if like == null 

    return Regex.IsMatch(
      source,
      "^" + Regex.Escape(like).Replace("_", ".").Replace("%", ".*") + "$");
  }
}

So you can put

string like = "%A%C%";
string source = "A B C";

if (source.ContainsLike(source, like)) {
  Console.Write("Matched"); 
} 
Share:
10,328
Ehsan Ullah Nazir
Author by

Ehsan Ullah Nazir

Updated on June 14, 2022

Comments

  • Ehsan Ullah Nazir
    Ehsan Ullah Nazir almost 2 years

    I have two strings for comparison

    String Str1 = "A C";
    String Str2 = "A B C";
    Str2.Contains(Str1); //It will return False ,Contains append % at Start and End of string 
    
    //Replace space with %
    Str1 = "%A%C%"; 
    Str2 = "%A%B%C%";
    Str2.Contains(Str1); //Want it to return True ,
    

    We do have Contains,StartsWith,EndsWith methods for comparison, But what my requirement is , if we compare str2 and str3 , it should return True , as it lies in Str2.

    Can we achive such behaviour in C# ?I have done this in SQL but not getting some useful at C#.Any regex etc ?