2011-03-07 47 views
0

我正在執行的教程中的過濾代碼如下發現: http://net.tutsplus.com/tutorials/javascript-ajax/using-jquery-to-manipulate-and-filter-data/篩選表數據,其中一個查詢的所有單詞的匹配

這是什麼基本上做的是找出哪些有你查詢的話,只有那些顯示的行行。問題是它在查詢的單詞之間使用OR。因此,如果我的查詢是「hello world」,它會向我顯示其中包含'hello'或'world'的行。

我想要做的是使用AND而不是OR,這樣行就會出現'hello'和'world'。代碼如下:

function filter(selector, query) { 
     query = $.trim(query); //trim white space 
     query = query.replace(/ /gi, '|'); //add OR for regex query 

     $(selector).each(function() { 
     ($(this).text().search(new RegExp(query, "i")) < 0) ? $(this).hide().removeClass('visible') : $(this).show().addClass('visible'); 
     }); 
    } 

謝謝你幫我出

回答

0

正如你所看到的,實施或正則表達式中的邏輯是非常簡單的。做AND邏輯是有點更環保。爲了達到這個目的,你可以在字符串的開始位置應用多個肯定的前瞻斷言。爲了說明如何可以做到這一點,這裏是用PHP編寫的一個註釋的正則表達式...

if (preg_match(
    '/# Match a string containing "word1" AND "word2" AND "word3". 
    ^    # Anchor to start of string 
    (?=.*?\bword1\b) # Ensure there is a "word1" in string 
    (?=.*?\bword2\b) # AND ensure there is a "word2" in string 
    (?=.*?\bword3\b) # AND ensure there is a "word3" in string 
    /ix', $contents)) { 
    # Successful match. All the words are in the $contents string. 
} else { 
    # Match attempt failed. 
} 

接下來你需要做的就是組裝使用Javascript類似的正則表達式。下面是一個和過濾功能:

function filter_AND(selector, query) { 
    query = query.split(/\s+/);   // Array of words to be matched. 
    var len = query.length;    // Save length for speed in loop. 
    var re_word = /^\w(?:.*\w)?$/;  // Regex to validate a single word. 
    var regex = '^';     // Begin assempling our "AND" regex. 
    for (var i = 0; i < len; ++i) {  // Loop adding each word to regex. 
     if (re_word.test(query[i])) { // If it begins and ends with '\w', 
      regex += '(?=.*?\\b' + query[i] + '\\b)'; // add word to regex. 
     } 
    } 
    regex = new RegExp(regex, 'i');  // Convert string to Regex object. 
    $(selector).each(function() { 
     ($(this).text().search(regex) < 0) ? 
      $(this).hide().removeClass('visible') : 
      $(this).show().addClass('visible'); 
     }); 
} 

希望這有助於! 8 ^)