0

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#$. If I want the same criteria but with a length of 16 it should return tingPassWord12#$.

This is what I have for a regular expression: (?=.*[A-Z].*[A-Z])(?=.*[!@#$&*])(?=.*[0-9].*[0-9])(?=.*[a-z].*[a-z].*[a-z]).{12}

That regex is based on this SO: Regex to validate password strength

I tried the following but it just returns the first 12 characters in the string instead of the matched string:

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?

Community
  • 1
  • 1
the4tress
  • 542
  • 6
  • 19
  • take a look it will help you http://stackoverflow.com/questions/24752474/password-regular-expression-for-atleast-2-digit-lowercase-uppercase – munsifali May 11 '16 at 06:33

1 Answers1

0

Solution using a simple for loop.

Basically it iterates through each substring of the desired length and checks if it matches the password conditions:

var str = 'testingtestingPassWord12#$testingtesting',
    re = /(?=(?:.*[A-Z]){2})(?=(?:.*[!@#$&*]){2})(?=(?:.*[0-9]){2})(?=(?:.*[a-z]){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;
timolawl
  • 5,434
  • 13
  • 29
  • That's what I have now but I wanted to avoid the for loop. In my code I'm trying to generate a secure password and validating the return on my code meets the criteria. So for example, my `encode('blah')` would return `hFaWPwh2X)vpz8Kiw&=NiwrfAwNYm9iw&JGgbrx2`. If a strong password isn't found in that string then it will reencode itself and keep trying until it finds a match. I was hoping either `str.match()` or `str.search()` would work. – the4tress May 11 '16 at 06:58
  • @the4tress not sure if there is a non-tedious way of doing it with `str.match()` or `str.search()` only. Maybe someone with greater regex powers can add their input. – timolawl May 11 '16 at 07:15