使用正則表達(dá)式實現(xiàn)像SQL中LIKE語句中的%和_通配

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

創(chuàng)新互聯(lián)專注為客戶提供全方位的互聯(lián)網(wǎng)綜合服務(wù),包含不限于成都網(wǎng)站建設(shè)、網(wǎng)站設(shè)計、寧縣網(wǎng)絡(luò)推廣、小程序開發(fā)、寧縣網(wǎng)絡(luò)營銷、寧縣企業(yè)策劃、寧縣品牌公關(guān)、搜索引擎seo、人物專訪、企業(yè)宣傳片、企業(yè)代運營等,從售前售中售后,我們都將竭誠為您服務(wù),您的肯定,是我們最大的嘉獎;創(chuàng)新互聯(lián)為所有大學(xué)生創(chuàng)業(yè)者提供寧縣建站搭建服務(wù),24小時服務(wù)熱線:18980820575,官方網(wǎng)址:bm7419.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;
        }
    }

 

首先,要將查詢串中所有正則表達(dá)式的元字符轉(zhuǎn)義為普通字符,這樣才能安全的使用正則表達(dá)式進(jìn)行匹配。

然后,將”_”和”%”替換成相應(yīng)的正則表達(dá)式,即”_”替換成”.”,”%”替換成”.*”。這里還考慮到SQL的LIKE語句也有轉(zhuǎn)義符功能,即如果使用ESCAPE子句則LIKE串中轉(zhuǎn)義符后的”_”和”%”變?yōu)槠胀ㄗ址皇峭ㄅ浞?。所以?dāng)使用轉(zhuǎn)義符時處理如下:

  • 將所有不以轉(zhuǎn)義符引導(dǎo)的通配符替換。

  • 再將轉(zhuǎn)義符引導(dǎo)的通配符的轉(zhuǎn)義符去掉,即將通配符轉(zhuǎn)義為普通字符。

以下是幾個轉(zhuǎn)換的例子:

  • LIKE ‘A_B’ 轉(zhuǎn)換為 A.B

  • LIKE ‘A%B’ 轉(zhuǎn)換為 A.*B

  • LIKE ‘A~_B’ ESCAPE ‘~’ 轉(zhuǎn)換為 A_B

  • LIKE ‘A.B’ 轉(zhuǎn)換為 A/.B

優(yōu)點:我們可以在LINQ語句的條件中方便的使用Like方法去過濾數(shù)據(jù),LINQ語句整體上會保持很好的可讀性。

缺點:Like 方法會被調(diào)用n次(n取決于數(shù)據(jù)量),解析SQL pattern到正則表達(dá)式pattern的代碼就要被重復(fù)執(zhí)行n次。因此當(dāng)數(shù)據(jù)量過大時解析pattern會消耗一定的資源。當(dāng)然這可以通過一些方法去解決,如緩存解析結(jié)果,或改為傳入就是解析好的正則表達(dá)式等。

文章題目:使用正則表達(dá)式實現(xiàn)像SQL中LIKE語句中的%和_通配
網(wǎng)站鏈接:http://bm7419.com/article46/jdophg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信公眾號、小程序開發(fā)網(wǎng)站收錄、網(wǎng)站排名定制網(wǎng)站、網(wǎng)站制作

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站托管運營