Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - how to ignore order of the matched groups? [duplicate]

I'm trying to create a regex validation for a password which is meant to be:

  1. 6+ characters long
  2. Has at least one a-z
  3. Has at least one A-Z
  4. Has at leat one 0-9

So, in other words, the match will have :

  1. at least one a-z, A-Z, 0-9
  2. at least 3 any other characters

I've came up with:

((.*){3,}[a-z]{1,}[A-Z]{1,}[0-9]{1,})

it seems pretty simple and logical to me, but 2 things go wrong:

  1. quantifier {3,} for (.*) somehow doesn't work and destroys whole regex. At first I had {6,} at the end but then regex would affect the quantifiers in inner groups, so it will require [A-Z]{6,} instead of [A-Z]{1,}
  2. when I remove {3,} the regex works, but will match only if the groups are in order - so that it will match aaBB11, but not BBaa11
like image 816
van_folmert Avatar asked Jan 21 '26 10:01

van_folmert


1 Answers

This is a use case where I wouldn't use a single regular expression, but multiple simpler ones.

Still, to answer your question: If you only want to validate that the password matches those criteria, you could use lookaheads:

^(?=.{6})(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9])

You're basically looking for a position from which you look at

  • 6 characters (and maybe more to follow, doesn't matter): (?=.{6})
  • maybe something, then a lowercase letter: (?=.*?[a-z])
  • maybe something, then an uppercase letter: (?=.*?[A-Z])
  • maybe something, then a digit: (?=.*?[0-9])

The order of appearance is arbitrary due to the maybe something parts.

(Note that I've interpreted 6 characters long as at least 6 characters long.)

like image 119
Marius Schulz Avatar answered Jan 23 '26 22:01

Marius Schulz