A regular expression matching at least n of m groups

I was going to write a regular expression that would only match if the string contains at least n different character classes. I was going to use this to get my users to create strong passwords and wanted to check if the password contains at least 3 of the following:

  • Characters
  • Characters of capital
  • The numbers
  • Special symbols

Writing a regular expression that matches if all of these classes are present is trivial using lookaheads. However, I cannot wrap my head around the β€œat least 3” part. Is this possible (in a nice, compact expression) or do I need to create a monster expression?

+6
source share
3 answers

I think this will be more compact than listing each possible combination of 3 out of 4. It uses a negative scan to make sure that the entire string does not consist of just one or two of the character classes you listed:

(?!([a-zA-Z]*|[az\d]*|[^AZ\d]*|[AZ\d]*|[^az\d]*|[^a-zA-Z]*)$).* 

In order, the following groups are here:

  • lower and / or upper
  • below and / or numbers
  • lower and / or special
  • upper and / or numbers
  • top and / or special
  • numbers and / or special

This regular expression will fail if the entire string (due to $ in a negative image) contains only characters from any of the above groups.

+6
source

You must write an expression for each possible combination of 3 out of 4 (a total of four expressions), and then | separate expressions together so that they pass if they execute at least one of the original expressions.

+2
source

What do you think of this decision?

 var str='23khkS_s'; var countGroups=0; if(str.match(/[az]+/)) countGroups++; if(str.match(/[AZ]+/)) countGroups++; if(str.match(/[0-9]+/)) countGroups++; if(str.match(/[ -_!@ #$%*\(\)]+/)) countGroups++; console.log(countGroups); 

Instead of using one monster-like expression, you can use 4 small REs. And then work with the variable countGroups , which contains the number of marked character groups. I hope this is helpful

0
source

Source: https://habr.com/ru/post/893016/


All Articles