Ehsan Ullah Nazir
Ehsan Ullah Nazir

Reputation: 1917

String comparison with Wildcard search in c#

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 ?

Upvotes: 3

Views: 19050

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

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"); 
} 

Upvotes: 7

Related Questions