c#中通配符搜索的字符串比较

时间:2022-09-13 07:52:23

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.

我们确实有Contains,StartsWith,EndsWith方法进行比较,但我的要求是,如果我们比较str2和str3,它应该返回True,因为它位于Str2中。

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

我们可以在C#中实现这样的行为吗?我在SQL中做过这个但是没有在C#中获得一些有用的东西。还有正则表达式等吗?

1 个解决方案

#1


2  

I suggest converting SQL-LIKE into regular expression:

我建议将SQL-LIKE转换为正则表达式:

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

#1


2  

I suggest converting SQL-LIKE into regular expression:

我建议将SQL-LIKE转换为正则表达式:

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