我在下面的教程中实现了过滤代码: 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 :(得分:0)
如您所见,在正则表达式中实现OR逻辑非常简单。做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组装一个类似的正则表达式。这是一个AND过滤功能:
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 ^)