简体   繁体   English

如何将字符串与 Javascript 中的模式数组匹配?

[英]How to match a string against an array of pattern in Javascript?

I've two variables:我有两个变量:

var input = "user1@gmail.com";
var preferredPatterns = ["*@gmail.com", "*@yahoo.com", "*@live.com"];

Want to match the input with preferred pattern array.想要将输入与首选模式数组匹配。 If any of the patterns matches I've to do certain task (in this example, input is a definite match).如果任何模式匹配,我必须执行某些任务(在此示例中,输入是确定匹配)。 How can I match against an array of pattern in javascript?如何匹配javascript中的模式数组?

You can compile your patterns (if they are valid regular expressions) into one for performance:您可以将您的模式(如果它们是有效的正则表达式)编译为一个以提高性能:

var masterPattern = new RegExp(patterns.join('|'));

Putting it all together:把它们放在一起:

var input = 'user1@gmail.com';
var preferredPatterns = [
  ".*@gmail.com$",
  ".*@yahoo.com$",
  ".*@live.com$"
];

var masterPattern = new RegExp(preferredPatterns.join('|'));

console.log(masterPattern.test(input));
// true

You need to use RegExp constructor while passing a variable as regex.在将变量作为正则表达式传递时,您需要使用RegExp构造函数。

var input = 'user1@gmail.com';
var preferredPatterns = [".*@gmail\\.com$", ".*@yahoo\\.com$", ".*@live\\.com$"];
for (i=0; i < preferredPatterns.length;i++) {
  if(input.match(RegExp(preferredPatterns[i]))) {
     console.log(preferredPatterns[i])
    }
    }

Dot is a special meta-character in regex which matches any character.点是正则表达式中的特殊元字符,可匹配任何字符。 You need to escape the dot in the regex to match a literal dot.您需要对正则表达式中的点进行转义以匹配文字点。

As @zerkms said, you could use the below list of patterns also.正如@zerkms 所说,您也可以使用下面的模式列表。

var preferredPatterns = ["@gmail\\.com$", "@yahoo\\.com$", "@live\\.com$"];

Try this helper function:试试这个辅助功能:

/**
 * Returns an integer representing the number of items in the patterns 
 * array that contain the target string text
 */
function check(str, patterns) {
   return patterns.reduce(function (previous, current) {
      return previous + (str.indexOf(current) == -1 ? 0 : 1);
    }, 0);
}

check("user@gmail.com", ["@gmail.com", "@yahoo.com", "@live.com"]; // returns 1
check("user@live.com", ["@gmail.com", "@yahoo.com", "@live.com"]; // returns 0

If you want a general approach to matching against a list of regular expressions then some version of Avinash Raj's answer will work.如果您想要一种匹配正则表达式列表的通用方法,那么 Avinash Raj 的答案的某些版本将起作用。

Based on the fact that you are specifying certain domains, you might want to match any valid email address using the regex here , and if it matches then check if the domain is a preferred one.基于您指定某些域的事实,您可能希望使用此处的正则表达式匹配任何有效的电子邮件地址,如果匹配,则检查该域是否是首选域。 There are a number of different ways you could do that of course.当然,您可以通过多种不同的方式来做到这一点。 Here's just a simple example, splitting on the @ and using jQuery.inArray() to check if the domain is preferred.这只是一个简单的例子,在@上拆分并使用jQuery.inArray()检查域是否是首选的。

var preferredDomains = ["gmail.com", "yahoo.com", "live.com"];

function isValid(inputVal) {
    var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;

    return re.test(inputVal) && $.inArray(inputVal.split('@')[1], preferredDomains) > -1;
}

The advantage here is that the underlying regex doesn't change, just the much easier to read/maintain list of domains.这里的优点是底层的正则表达式不会改变,只是更容易阅读/维护域列表。 You could tweak this to capture the domain in a group, instead of using split().您可以调整它以捕获组中的域,而不是使用 split()。

preferredPatterns.forEach(function(element, index){ 
   if(input.match('/'+element) != null){ 
      console.log('matching  ' + element)  
   }
})

you can write your custom logic if a string matches any pattern.如果字符串匹配任何模式,您可以编写自定义逻辑。

No regexp you may do as follows;没有正则表达式你可以做如下;

 function matchPattern(xs, [y,...ys]){ function helper([x,...xs]){ return "*" + xs.join('') === y ? true : xs.length ? helper(xs) : false; } return helper(xs) ? y : ys.length ? matchPattern(xs,ys) : "No Match..!"; } var input = "user1@gmail.com", preferredPatterns = ["*@yahoo.com", "*@live.com", "*@gmail.com"]; result = matchPattern(input, preferredPatterns); console.log(result);

您可以遍历数组,然后使用正则表达式与单个项目进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM