简体   繁体   English

JavaScript在字符串中查找复杂正则表达式的第一个匹配项

[英]JavaScript Find first match of complex regex in string

I'm trying to write a script that deals with passwords. 我正在尝试编写一个处理密码的脚本。 I want to find the first match on a regular expression in a long string. 我想在长字符串中找到正则表达式的第一个匹配项。 For example, if I have the string testingtestingPassWord12#$testingtesting and I want to find the first instance that has 2 uppercase, 2 lowercase, 2 numbers, 2 special characters and a minimum length of 12, it should return PassWord12#$ . 例如,如果我具有字符串testingtestingPassWord12#$testingtesting并且我想找到第一个实例,该实例具有2个大写字母,2个小写字母,2个数字,2个特殊字符以及最小长度为12,则应返回PassWord12#$ If I want the same criteria but with a length of 16 it should return tingPassWord12#$ . 如果我想要相同的条件,但长度为16,则应返回tingPassWord12#$

This is what I have for a regular expression: (?=.*[AZ].*[AZ])(?=.*[!@#$&*])(?=.*[0-9].*[0-9])(?=.*[az].*[az].*[az]).{12} 这是我的正则表达式: (?=.*[AZ].*[AZ])(?=.*[!@#$&*])(?=.*[0-9].*[0-9])(?=.*[az].*[az].*[az]).{12}

That regex is based on this SO: Regex to validate password strength 该正则表达式基于以下SO:正则表达式以验证密码强度

I tried the following but it just returns the first 12 characters in the string instead of the matched string: 我尝试了以下操作,但是它只是返回字符串中的前12个字符,而不是匹配的字符串:

var str = 'testingtestingPassWord12#$testingtesting',
    re = /(?=.*[A-Z].*[A-Z])(?=.*[!@#$&*])(?=.*[0-9].*[0-9])(?=.*[a-z].*[a-z].*[a-z]).{12}/;

console.log(str.match(re));


// Output: ["testingtestingPa"]

What am I missing? 我想念什么?

Solution using a simple for loop. 使用简单的for循环的解决方案。

Basically it iterates through each substring of the desired length and checks if it matches the password conditions: 基本上,它会遍历所需长度的每个子字符串,并检查其是否符合密码条件:

 var str = 'testingtestingPassWord12#$testingtesting', re = /(?=(?:.*[AZ]){2})(?=(?:.*[!@#$&*]){2})(?=(?:.*[0-9]){2})(?=(?:.*[az]){2}).{12,}/; var substring, res = ''; var passwordLength = 12; for (var i = 0; i < str.length - passwordLength; i++) { substring = str.substr(i, passwordLength); if(substring.match(re)) { res = substring.match(re); break; } } document.body.textContent = res; 

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

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