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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10152650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:05:17  来源:igfitidea点击:

javascript - match regular expression against the array of items

javascriptarraysexpression

提问by user398341

Is there a way in JavaScript to get Boolean value for a match of the string against the array of regular expressions?

JavaScript 中有没有办法获取字符串与正则表达式数组匹配的布尔值?

The example would be (where the 'if' statement is representing what I'm trying to achieve):

示例是(其中“if”语句代表我要实现的目标):

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

if (matchInArray(thisString, thisExpressions)) {

} 

采纳答案by GillesC

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

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)?

回答by andersh

Using a more functional approach, you can implement the match with a one-liner using an array function:

使用更实用的方法,您可以使用数组函数实现单行匹配:

ECMAScript 6:

ECMAScript 6:

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

ECMAScript 5:

ECMAScript 5:

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

回答by Likwid_T

You could use .test()which returns a boolean value when is find what your looking for in another string:

您可以使用.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 */ }

回答by Daniel Arenas

look this way...

这边看...

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

回答by bitifet

You can join all regular expressions into single one. This way the string is scanned only once. Even with a sligthly more complex regular expression.

您可以将所有正则表达式合并为一个。这样字符串只被扫描一次。即使使用稍微复杂的正则表达式。

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!!");
} 

In fact, even with this approach, if you need check the same expression set against multiple strings, this is a few suboptimal because you are building (and compiling) the same regular expression each time the function is called.

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

Better approach would be to use a function builder like this:

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

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!!");
} 

回答by Mubeen Khan

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

let str = 'else';

here will be the check for following expressions:

这里将检查以下表达式:

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

}

using Array .find() method to traverse array and .include to check substring

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

回答by Mod

So we make a function that takes in a literal string, and the array we want to look through. it returns a new array with the matches found. We create a new regexp object inside this function and then execute a String.search on each element element in the array. If found, it pushes the string into a new array and returns.

所以我们创建了一个函数,它接收一个字符串,以及我们想要查看的数组。它返回一个新数组,其中包含找到的匹配项。我们在此函数中创建一个新的 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)