检查多个字符串是否匹配多个正则表达式(两个数组)

Check multiple strings for matching multiple regex (both array)

本文关键字:数组 两个 字符串 是否 检查 正则表达式      更新时间:2023-09-26

我需要检查数组(字符串)的所有元素是否匹配任何正则表达式,正则表达式也存储在数组中。

那么这里是字符串数组和和正则表达式数组(在这个例子中,所有三个元素都是相同的正则表达式-我知道这没有意义):

let array = [ 'just some', 'strings', 'which should be tested', 'by regex' ];
let regexes = [ /([^.]+)[.'s]*/g, /([^.]+)[.'s]*/g, /([^.]+)[.'s]*/g ];

现在我要做两个这样的_.each循环:

_.each(array, function(element) {
    _.each(regexes, function(regex) {
        let match = regex.exec(element);
        if (match && match.length)
            doSomething(match);
    });
});

但是我想要实现的是,如果只有一个正则表达式匹配,我想处理这个字符串。因此,对于这个无意义的正则表达式数组,这种情况永远不会发生,因为将没有或三个匹配的正则表达式。

此外,我想知道是否有可能避免这种嵌套的each循环。

的例子:

let array = [ '1. string', 'word', '123' ]
let regexes = [/([a-z]+)/, /([0-9]+)/]
array[0] should NOT pass the test, as both regex are matching
array[1] should pass the test, as just ONE regex is matching
array[2] should pass the test, as just ONE regex is matching

,因此只有数组[1]和数组[2]的结果应该用于进一步处理doSomething(match)

您可以使用Array#reduce并计算匹配。如果count等于1,则继续处理。

var array = ['1. string', 'word', '123'],
    regexes = [/([a-z]+)/, /([0-9]+)/];
array.forEach(function (a) {
    var match,
        count = regexes.reduce(function (count, r) {
            var test = r.exec(a);
            if (!test) {
                return count;
            }
            match = test;
            return count + 1;
        }, 0);
    count === 1 && console.log(match);
});

可以合并Array.prototype.filterArray.prototype.every:

let array = ['1. string', 'word', '123'],
  regexes = [/([a-z]+)/, /([0-9]+)/];
var result = array.filter(str => {
  var count = 0;
  return regexes.every(reg => {
    reg.test(str) && count++;
    return count <= 1;
  });
});
console.log(result)