正则表达式支持LIKE
所允许的一切,甚至更多,但其语法完全不同.然而,由于LIKE
的规则非常简单(其中%
表示零个或多个字符,_
表示一个字符),并且LIKE
个参数和正则表达式都是用字符串表示的,因此我们可以创建一个正则表达式,它接受LIKE
个参数(例如abc_ef% *usd
),并将其转换为等价的正则表达式(例如\Aabc.ef.* \*usd\z
):
@"\A" + new Regex(@"\.|\$|\^|\{|\[|\(|\||\)|\*|\+|\?|\\").Replace(toFind, ch => @"\" + ch).Replace('_', '.').Replace("%", ".*") + @"\z"
基于此,我们可以构建一个Like()
方法:
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");