Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

Something like Sql LIKE would be very useful.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
295 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

And hence:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...