C#版本的SQL LIKE版本、SQL、LIKE

2023-09-02 11:56:25 作者:爱欲与孤独

有没有什么办法来搜索字符串的模式在C#?

Is there any way to search patterns in strings in C#?

东西,如SQL LIKE将是非常有益的。

Something like Sql LIKE would be very useful.

推荐答案

普通EX pressions允许的一切, LIKE 允许,等等,但一个完全不同的语法。然而,由于规则 LIKE 是如此简单(其中表示零或更多的字符和 _ 表示一个字符),无一不 LIKE 参数,并定期EX pressions是pssed在字符串中的前$ P $,我们可以创建一个普通的前pression,需要一个 LIKE 参数(如 abc_ef%*美元),并把它成等价的普通恩pression(如 Aabc.ef. * * USD Z ):

Regular expressions allow for everything that LIKE allows for, and much more, but have a completely different syntax. However, since the rules for LIKE are so simple(where % means zero-or-more characters and _ means one character), and both LIKE arguments and regular expressions are expressed in strings, we can create a regular expression that takes a LIKE argument (e.g. abc_ef% *usd) and turn it into the equivalent regular expression (e.g. Aabc.ef.* *usdz):

@"A" + new Regex(@".|$|^|{|[|(|||)|*|+|?|\").Replace(toFind, ch => @"" + ch).Replace('_', '.').Replace("%", ".*") + @"z"

这是我们可以建立一个赞()方法:

From that we can build a Like() method:

public static class MyStringExtensions
{
  public static bool Like(this string toSearch, string toFind)
  {
    return new Regex(@"A" + new Regex(@".|$|^|{|[|(|||)|*|+|?|\").Replace(toFind, ch => @"" + ch).Replace('_', '.').Replace("%", ".*") + @"z", RegexOptions.Singleline).IsMatch(toSearch);
  }
}

因此​​:

bool willBeTrue = "abcdefg".Like("abcd_fg");
bool willAlsoBeTrue = "abcdefg".Like("ab%f%");
bool willBeFalse = "abcdefghi".Like("abcd_fg");