Click here to Skip to main content
15,885,309 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I want to check a password which fulfills the following criteria:
at least 1 uppercase letter
at least 1 lowercase letter
at least 1 digit
at least 1 ASCII character
But I want regex to match in no specific order; for example when I typed the regex given in section (What have you tried) below, it didn't match orderless; it required the input to be in order with the regex.

What I have tried:

/([a-z][A-Z][0-9][!@#$%&])/g
Posted
Updated 22-Apr-22 0:05am

The problem is that Regular Expressions are text processors, not logic engines - they aren't designed to do rules based operations.
And that is exactly what you are asking for: to do counting and act on rules.

So by all means use Regexes to identify if characters are present in a string, but process the rules based on that in code, don't try to do it all in a text processor.

Think about it: even if your could do exactly what you wanted, what happens next week when the rules change and require a special character as well from a specific list? Implemented in code it's trivial to understand and modify - which is not the case with any regex beyond the trivial examples!

Regex is a tool in your box - but that doesn't mean it should be used at every opportunity: a hammer can be used on screws, but a screwdriver does a better job!
 
Share this answer
 
Comments
Patrice T 21-Apr-22 16:58pm    
Hi OG,
I think your answer How to set validation for the password in javascript using regex?[^]
match this question.
OriginalGriff 21-Apr-22 17:30pm    
Just because you can do something, doesn't mean you should! :laugh:
Quote:
What is the problem with regex when checking at least 1 uppercase letter, 1 lowercase letter, 1 digit where the expression can be in no particular order

The problem is that RegEx is not really designed for this, the solution is rather tricky.
As OG answered sometime ago : How to set validation for the password in javascript using regex?[^]
Try something like :
^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%&]).*$


Just a few interesting links to help building and debugging RegEx.
Here is a link to RegEx documentation:
perlre - perldoc.perl.org[^]
Here is links to tools to help build RegEx and debug them:
.NET Regex Tester - Regex Storm[^]
Expresso Regular Expression Tool[^]
RegExr: Learn, Build, & Test RegEx[^]
Online regex tester and debugger: PHP, PCRE, Python, Golang and JavaScript[^]
This one show you the RegEx as a nice graph which is really helpful to understand what is doing a RegEx: Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]
This site also show the Regex in a nice graph but can't test what match the RegEx: Regexper[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900