javascript - 将正则表达式与项数组匹配

时间:2012-04-14 09:50:47

标签: javascript arrays expression

JavaScript中是否有一种方法可以获得字符串与正则表达式数组匹配的布尔值?

示例将是(其中'if'语句表示我正在尝试实现的目标):

var thisExpressions = [ '/something/', '/something_else/', '/and_something_else/'];
var thisString = 'else';

if (matchInArray(thisString, thisExpressions)) {

} 

8 个答案:

答案 0 :(得分:57)

使用功能更强大的方法,您可以使用array function实现与单线的匹配:

ECMAScript 6:

const regexList = [/apple/, /pear/];
const text = "banana pear";
const isMatch = regexList.some(rx => rx.test(text));

ECMAScript 5:

var regexList = [/apple/, /pear/];
var text = "banana pear";
var isMatch = regexList.some(function(rx) { return rx.test(text); });

答案 1 :(得分:15)

http://jsfiddle.net/9nyhh/1/

var thisExpressions = [/something/, /something_else/, /and_something_else/];
var thisExpressions2 = [/else/, /something_else/, /and_something_else/];
var thisString = 'else';

function matchInArray(string, expressions) {

    var len = expressions.length,
        i = 0;

    for (; i < len; i++) {
        if (string.match(expressions[i])) {
            return true;
        }
    }

    return false;

};

setTimeout(function() {
    console.log(matchInArray(thisString, thisExpressions));
    console.log(matchInArray(thisString, thisExpressions2));
}, 200)​

答案 2 :(得分:5)

您可以使用.test()在找到您在另一个字符串中查找的内容时返回一个布尔值:

var thisExpressions = [ '/something/', '/something_else/', '/and_something_else/'];
var thisString = new RegExp('\\b' + 'else' + '\\b', 'i');
var FoundIt = thisString.test(thisExpressions);  
if (FoundIt) { /* DO STUFF */ }

答案 3 :(得分:1)

这样看......

function matchInArray(stringSearch, arrayExpressions){
    var position = String(arrayExpressions).search(stringSearch);
    var result = (position > -1) ? true : false
    return result;
}

答案 4 :(得分:1)

您可以将所有正则表达式合并为一个。这样的字符串是 仅扫描一次。即使使用复杂得多的正则表达式。

var thisExpressions = [ /something/, /something_else/, /and_something_else/];
var thisString = 'else';


function matchInArray(str, expr) {
    var fullExpr = new RegExp(expr
        .map(x=>x.source) // Just if you need to provide RegExp instances instead of strings or ...
        // .map(x=>x.substring(1, x.length -2)  // ...if you need to provide strings enclosed by "/" like in original question.
        .join("|")
    )
    return str.match(fullExpr);

};


if (matchInArray(thisString, thisExpressions)) {
    console.log ("Match!!");
} 

实际上,即使使用这种方法,如果需要检查相同的表达式集 针对多个字符串,这是次优的,因为您正在构建 每次调用该函数时(都会编译)相同的正则表达式。

更好的方法是使用像这样的函数构建器:

var thisExpressions = [ /something/, /something_else/, /and_something_else/];
var thisString = 'else';

function matchInArray_builder(expr) {
    var fullExpr = new RegExp(expr
        .map(x=>x.source) // Just if you need to provide RegExp instances instead of strings or ...
        // .map(x=>x.substring(1, x.length -2)  // ...if you need to provide strings enclosed by "/" like in original question.
        .join("|")
    )   

    return function (str) {
        return str.match(fullExpr);

    };
};  

var matchInArray = matchInArray_builder(thisExpressions);

if (matchInArray(thisString)) {
    console.log ("Match!!");
} 

答案 5 :(得分:1)

考虑将这个问题分为两部分:

  1. filter排除match给定正则表达式的项目
  2. 确定该过滤列表中是否有0个匹配项
const sampleStringData = ["frog", "pig", "tiger"];

const matches = sampleStringData.filter((animal) => /any.regex.here/.test(animal));

if (matches.length === 0) {
  console.log("No matches");
}

答案 6 :(得分:0)

let expressions = [ '/something/', '/something_else/', '/and_something_else/'];

let str = 'else';

这是对以下表达式的检查:

if( expressions.find(expression => expression.includes(str) ) ) {

}

使用Array .find()方法遍历数组,并使用.include检查子字符串

答案 7 :(得分:-1)

所以我们创建一个函数,它接受一个文字字符串,以及我们想要查看的数组。它返回一个找到匹配项的新数组。我们在这个函数中创建一个新的regexp对象,然后对数组中的每个元素元素执行一个String.search。如果找到,它会将字符串推入新数组并返回。

// literal_string: a regex search, like /thisword/ig
// target_arr: the array you want to search /thisword/ig for.

function arr_grep(literal_string, target_arr) {
  var match_bin = [];
  // o_regex: a new regex object.
  var o_regex = new RegExp(literal_string);
  for (var i = 0; i < target_arr.length; i++) {
    //loop through array. regex search each element.
    var test = String(target_arr[i]).search(o_regex);
    if (test > -1) {
    // if found push the element@index into our matchbin.
    match_bin.push(target_arr[i]);
    }
  }
  return match_bin;
}

// arr_grep(/.*this_word.*/ig, someArray)