搜索数组中的多个元素

时间:2017-08-09 12:18:11

标签: javascript arrays regex

我想在数组全部内检索匹配多个字符串的元素(所有这些&不必要的字):就像搜索引擎返回所有结果匹配 @IBAction func move(_ sender: UIButton) { if !isActive { DispatchQueue.main.async { UIView.animate(withDuration: 0.25, animations: { self.word.frame.origin.y -= self.bounds.height / 7 }, completion: nil) UIView.animate(withDuration: 0.3, animations: { self.translation.alpha = 1 self.exOne.alpha = 1 self.exTwo.alpha = 1 }) } isActive = true } else { DispatchQueue.main.async { UIView.animate(withDuration: 0.25, animations: { self.word.frame.origin.y += self.bounds.height / 7 }, completion: nil) UIView.animate(withDuration: 0.3, animations: { self.translation.alpha = 0 self.exOne.alpha = 0 self.exTwo.alpha = 0 }) } isActive = false } } } override func prepareForReuse() { super.prepareForReuse() self.word.frame.origin.y = self.wordTop.constant, //where wordTop is a top constraint for the word isActive = false self.translation.alpha = 0 self.exOne.alpha = 0 self.exTwo.alpha = 0 } && term_searched#1

这不是关于数组中term_searched#2的问题(没有),而是关于搜索元素的连接:传统上,搜索是对于一个元素,单独或与分离与其他元素(a | b | c)。只想搜索(&& b&& c)。

我试过了:

  • duplicates:我只能使用一个元素来定位数组。
  • indexOf()match()表达式中没有AND运算符(仅regex - 遗憾的是,它会simple}。所以我试着注入这些|表达式
    • regex
    • /(?=element1).*(?=element2)/gim请参阅here

第一个/(?=element1)(?=element2)/gim表达式有效,但不是每次都有效:看起来非常脆弱......

所以我不知道我是否朝着好的方向前进(regex),或者我是否能够找出正确的match表达方式......需要你的建议。

regex

根据Gawil的回答进行编辑,以适应我的初始代码(如果需要,可以提供帮助)

// filter grid by searching on 'input' event
'input #search': (e)=> {
    var keypressed = e.currentTarget.value;

    // create array on 'space' input
    var keyarr = keypressed.toLowerCase().split(" ");

    // format each array's element into regex expression
    var keyarrReg = [];
    for(i = 0; i < keyarr.length; i++) {
        var reg = '(?=' + keyarr[i] + ')';
        keyarrReg.push(reg);
    }

    // array to regex string into '/(?=element1).*(?=element2)/gim' format
    var searching = new RegExp(keyarrReg.join(".*"), 'mgi');

    // set grid
    var grid = new Muuri('#gridre', {
        layout: {
            fillGaps: true,
        }
    });

    if (keypressed) {
        // filter all grid's items (grid of items is an array)
        grid.filter(function (item) {
            var searchoperator = item.getElement().textContent.toLowerCase().match(searching);
            // get items + only their text + lower case their text + return true (not false) in the value ('keypressed') is found in them
            //var searchoperator = item.getElement().textContent.toLowerCase().indexOf(keypressed.toLowerCase()) != -1;
            return searchoperator;
        }
        [....]

    }
}

1 个答案:

答案 0 :(得分:3)

下面的代码将记录包含单词catsdogs的数组的每个元素 它使用正则表达式^(?=.*word1)(?=.*word2).*$来处理新行,请改用它:
^(?=(?:.|\n)*word1)(?=(?:.|\n)*word2).*$

您可以按照相同的逻辑添加任意数量的单词,并且不会计算单词中的单词顺序。

它与您尝试的非常相似,只是您必须在匹配字符串之前执行所有(?=)次检查。实际上,您的第一个正则表达式只有在单词顺序正确时才会起作用(element1然后是element2)。你的第二个正则表达式几乎可以工作,但是你只编写了前瞻,所以它会检查每个单词的存在,但不会匹配任何单词。

var words = ["cats", "dog"]
var array = [
  "this is a string",
  "a string with the word cats",
  "a string with the word dogs",
  "a string with both words cats and dogs",
  "cats rule everything",
  "dogs rule cats",
  "this line is for dog\nbut cats prefer this one"
]

var regexString = "^";
words.forEach(function(word) { regexString += ("(?=(?:.|\n)*"+word+")"); });

var regex = new RegExp(regexString);

array.forEach(function(str) { // Loop through the array
  if(str.match(regex)) {
    console.log(str); // Display if words have been found
  }
});