javascript 针对javascript中的多个正则表达式的测试字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10921321/
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-10-26 11:28:44  来源:igfitidea点击:

test string against multiple regexes in javascript

javascriptregex

提问by mark

I want to test a given string against 20 or so regular expressions. What's a clean way to do this in Javascript? I'm more concerned about clean code and readability than efficiency (but I don't want it to be super slow either).

我想针对 20 个左右的正则表达式测试给定的字符串。在 Javascript 中执行此操作的干净方法是什么?我更关心干净的代码和可读性而不是效率(但我也不希望它超级慢)。

Right now I have:

现在我有:

if (href.indexOf('apple.com') > -1 ||
    href.indexOf('google.com') > -1 ||
    href.indexOf('yahoo.com') > -1 ||
    href.indexOf('facebook.com') > -1) {
    performDarkMagic()
}

But it's going to start looking kind of messy as that list grows. Maybe I could just create an array of regular expressions and execute something like _.any() and apply regex.test on each?

但随着该列表的增长,它会开始看起来有点混乱。也许我可以创建一个正则表达式数组并执行诸如 _.any() 之类的东西并在每个表达式上应用 regex.test ?

Edit: the strings/regexes to match may become more complicated, I just used simple URLs to make the example readable.

编辑:要匹配的字符串/正则表达式可能会变得更复杂,我只是使用简单的 URL 使示例可读。

回答by Larry Battle

Use the test function for regular expressions.

对正则表达式使用 test 函数。

More information on regular expressions here. https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp

有关正则表达式的更多信息,请点击此处。 https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp

var re = /((google)|(facebook)|(yahoo)|(apple))\.com/;
re.test( str ); // returns true or false;

Test cases.

测试用例。

Live Demo Here: http://jsfiddle.net/rkzXP/1/

现场演示:http: //jsfiddle.net/rkzXP/1/

    var func = function( str ){
        var re = /((google)|(facebook)|(yahoo)|(apple))\.com/;
        return re.test( str );
    };
    test("test for valid values", function() {
        equal( func("google.com"), true);
        equal( func("facebook.com"), true);
        equal( func("apple.com"), true);
    });
    test("test for invalid values", function() {
        equal( func("googl.com"), false);
        equal( func("faceook.com"), false);
        equal( func("apple"), false);
    });

So you can rewrite your code as the following.

因此,您可以将代码重写为如下所示。

var re = /((google)|(facebook)|(yahoo)|(apple))\.com/;
if( re.test(str) ){
    performDarkMagic()
}

回答by Hunter McMillen

var patterns = ['apple.com', 'google.com', 'yahoo.com', 'facebook.com', ...]
var callFunc = false;

patterns.forEach(function(item){
   if(href.indexOf(item) > -1){
       callFunc = true;
       break;
   }
});

if(callFunc) {
   performDarkMagic();
}

回答by Bergi

Yes, building an array and using .any()or .some()is just fine, especially when there will be more than 4 values:

是的,构建一个数组并使用.any()or.some()就好了,尤其是当有超过 4 个值时:

if (["apple","google","yahoo","facebook"].some(host => href.includes(`${host}.com`)) {
    performLightMagic();
}

Yet I can't see regexes there, there are just strings; so you could simplify using regex.test()to:

但是我在那里看不到正则表达式,只有字符串;所以你可以简化使用regex.test()

if (/apple\.com|google\.com|yahoo\.com|facebook\.com/.test(href)) { performLightMagic(); }

or even

甚至

if (/(apple|google|yahoo|facebook)\.com/.test(href)) { performLightMagic(); }

回答by Daniel A. White

You could put each one in array then looping over each.

你可以把每个都放在数组中,然后循环遍历每个。

回答by tronbabylove

How I would do it: factor it out into a function. Put each regex in an array, loop over them and return true the first time indexOf > -1. If you reach the end of the loop return false.

我会怎么做:把它分解成一个函数。将每个正则表达式放入一个数组中,循环它们并在第一次 indexOf > -1 时返回 true。如果到达循环末尾,则返回 false。

回答by Nicolás Torres

Loop through a regex array and then do:

循环遍历一个正则表达式数组,然后执行:

result=result AND (result_of_regex);

next;

after the loop return result

循环返回结果后