在项目中我们经常遇到将数据库的数据取到后再次进行筛选过滤的情况。LINQ to Entity提供了统一的查询接口并且可以高效的完成工作,但是对于我们常在SQL中使用的%和_这样的通配符并没有支持。我们只能通过String.Contains方法来实现简单的通配。使用String.Contains方法是无法达到在查询串中使用通配符的目的的。正则表达式虽然晦涩难懂,但功能十分强大,解决个统配符绰绰有余。
代码如下:
public static class LINQHelper
{
/// <summary>
/// The all regex meta chars
/// </summary>
private static string[] REGEX_META_CHARS = { "\\", ".", "^", "$", "*", "+", "?", "{", "}", "(", ")", "[", "]" };
/// <summary>
/// Like method work as SQL like
/// </summary>
/// <param name="searchString">The search string</param>
/// <param name="sqlPattern">The SQL pattern</param>
/// <returns>Whether match or not</returns>
public static bool Like(this string searchString, string sqlPattern)
{
if (searchString == null)
{
return false;
}
else
{
string convertedPattern = EscapeRegexMetaChars(sqlPattern).Replace("_", ".").Replace("%", ".*");
convertedPattern = String.Format("^{0}$", convertedPattern);
return Regex.IsMatch(searchString, convertedPattern, RegexOptions.Singleline);
}
}
/// <summary>
/// Like method work as SQL like
/// </summary>
/// <param name="searchString">The search string</param>
/// <param name="sqlPattern">The SQL pattern</param>
/// <param name="escapeChar">The escape char</param>
/// <returns>Whether match or not</returns>
public static bool Like(this string searchString, string sqlPattern, char escapeChar)
{
if (searchString == null)
{
return false;
}
else
{
string convertedPattern = EscapeRegexMetaChars(sqlPattern);
convertedPattern = ReplaceWildcards(convertedPattern, '_', ".", escapeChar);
convertedPattern = ReplaceWildcards(convertedPattern, '%', ".*", escapeChar);
convertedPattern = String.Format("^{0}$", convertedPattern);
return Regex.IsMatch(searchString, convertedPattern, RegexOptions.Singleline);
}
}
/// <summary>
/// Replace wildcards
/// </summary>
/// <param name="replacement">The replacement string</param>
/// <param name="wildcard">The wildcard</param>
/// <param name="replaceTo">The replace wild char to</param>
/// <param name="escapeChar">The escape char</param>
/// <returns>The converted search value</returns>
private static string ReplaceWildcards(string replacement, char wildcard, string replaceTo, char escapeChar)
{
string regexExpression = String.Format("(^|[^{0}])({1}+)", escapeChar, wildcard);
return Regex.Replace(replacement, regexExpression, match => String.Format("{0}{1}", match.Groups[1].Value, match.Groups[2].Value.Replace(wildcard.ToString(), replaceTo)))
.Replace(string.Format("{0}{1}", escapeChar, wildcard), wildcard.ToString());
}
/// <summary>
/// Escape regex meta chars
/// </summary>
/// <param name="replacement">The replacement string</param>
/// <returns>The converted search value</returns>
private static string EscapeRegexMetaChars(string replacement)
{
string resultString = replacement;
foreach (string metaChar in REGEX_META_CHARS)
{
resultString = resultString.Replace(metaChar, string.Format(@"\{0}", metaChar));
}
return resultString;
}
}
首先,要将查询串中所有正则表达式的元字符转义为普通字符,这样才能安全的使用正则表达式进行匹配。
然后,将”_”和”%”替换成相应的正则表达式,即”_”替换成”.”,”%”替换成”.*”。这里还考虑到SQL的LIKE语句也有转义符功能,即如果使用ESCAPE子句则LIKE串中转义符后的”_”和”%”变为普通字符而不是通配符。所以当使用转义符时处理如下:
将所有不以转义符引导的通配符替换。
再将转义符引导的通配符的转义符去掉,即将通配符转义为普通字符。
以下是几个转换的例子:
LIKE ‘A_B’ 转换为 A.B
LIKE ‘A%B’ 转换为 A.*B
LIKE ‘A~_B’ ESCAPE ‘~’ 转换为 A_B
LIKE ‘A.B’ 转换为 A/.B
优点:我们可以在LINQ语句的条件中方便的使用Like方法去过滤数据,LINQ语句整体上会保持很好的可读性。
缺点:Like 方法会被调用n次(n取决于数据量),解析SQL pattern到正则表达式pattern的代码就要被重复执行n次。因此当数据量过大时解析pattern会消耗一定的资源。当然这可以通过一些方法去解决,如缓存解析结果,或改为传入就是解析好的正则表达式等。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。