C# Version Of SQL LIKE

后端 未结 20 2292
天涯浪人
天涯浪人 2020-11-29 02:12

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

Something like Sql LIKE would be very useful.

20条回答
  •  难免孤独
    2020-11-29 02:32

    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.* \*usd\z):

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

    And hence:

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

提交回复
热议问题