在項目中我們經常遇到將數據庫的數據取到后再次進行篩選過濾的情況。LINQ to Entity提供了統一的查詢接口并且可以高效的完成工作,但是對于我們常在SQL中使用的%和_這樣的通配符并沒有支持。我們只能通過String.Contains方法來實現簡單的通配。使用String.Contains方法是無法達到在查詢串中使用通配符的目的的。正則表達式雖然晦澀難懂,但功能十分強大,解決個統配符綽綽有余。

創新互聯專注為客戶提供全方位的互聯網綜合服務,包含不限于成都網站建設、網站設計、寧縣網絡推廣、小程序開發、寧縣網絡營銷、寧縣企業策劃、寧縣品牌公關、搜索引擎seo、人物專訪、企業宣傳片、企業代運營等,從售前售中售后,我們都將竭誠為您服務,您的肯定,是我們最大的嘉獎;創新互聯為所有大學生創業者提供寧縣建站搭建服務,24小時服務熱線:18980820575,官方網址:www.yijiale78.com
代碼如下:
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會消耗一定的資源。當然這可以通過一些方法去解決,如緩存解析結果,或改為傳入就是解析好的正則表達式等。
文章題目:使用正則表達式實現像SQL中LIKE語句中的%和_通配
網站鏈接:http://www.yijiale78.com/article46/jdophg.html
成都網站建設公司_創新互聯,為您提供微信公眾號、小程序開發、網站收錄、網站排名、定制網站、網站制作
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯