我需要检查数组的所有元素(字符串)是否与任何正则表达式匹配,正则表达式也存储在数组中。
所以这是字符串数组和regex数组(在此示例中,所有三个元素都是相同的regex-我知道这没有意义):
let array = [ 'just some', 'strings', 'which should be tested', 'by regex' ];
let regexes = [ /([^.]+)[.\s]*/g, /([^.]+)[.\s]*/g, /([^.]+)[.\s]*/g ];
现在,我将_.each
像这样执行两个-loops:
_.each(array, function(element) {
_.each(regexes, function(regex) {
let match = regex.exec(element);
if (match && match.length)
doSomething(match);
});
});
但是我要实现的是,如果只有一个正则表达式匹配,我想处理此字符串。因此,对于这种毫无意义的正则表达式数组,情况将永远不会如此,因为将不存在或只有三个匹配的正则表达式。
此外,我想知道是否有可能避免此嵌套的每个循环。
更新
例子:
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
因此,仅应将array [1]和array [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);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句