1

So I'm using Regex to create a change password form. Some text updates to "weak", "average", "strong" and "perfect" based on the passwords strength. I've managed to create a regex string that checks for all characters active as you can see in this string here which I would then compare with the new password string...

Regex rgxAll = new Regex(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*(_|[^\w])).+$");

Though what I'm trying to do now is create a string that checks: "Does the new password contain a lowercase character AND an uppercase character OR a special character OR a number" So to simplify it into coding terms...

NewPass.IsMatch(lowercaseLetter &&(uppercaseLetter || specialChar || number);

So yeah, I'm looking to create a regex that I can use IsMatch on to check. I've tried looking online but the syntax of regex is confusing to me.

Lewis
  • 566
  • 4
  • 21
  • Put those patterns you ORed into 1 lookahead. – Wiktor Stribiżew May 11 '18 at 06:58
  • How would that look? Sorry I'm not familiar with Regex at all – Lewis May 11 '18 at 07:02
  • Possible duplicate of [regex pattern lowercase and uppercase and number OR special character](https://stackoverflow.com/questions/41883854/regex-pattern-lowercase-and-uppercase-and-number-or-special-character) – Maciej Los May 11 '18 at 07:09
  • 1
    Just a note on style, I wouldn't use "perfect". ;) – Immersive May 11 '18 at 07:15
  • I have just thought about a pattern like `^(?=[^a-z]*[a-z])(?=[a-z]*[^a-z]).*` - it will require at least 1 lowercase and at least 1 char other than lowercase ASCII letter. It is not quite the same but might be something you can consider. – Wiktor Stribiżew May 11 '18 at 07:28
  • You should read [Reference - Password Validation](https://stackoverflow.com/questions/48345922/reference-password-validation) – ctwheels May 30 '18 at 15:37

2 Answers2

3

You can use the following:

^(?=.*[a-z])(?=.*[A-Z\W\d_])

Exp:

  • (?=.*[a-z]) : lookahead for lowercase letter
  • (?=.*[A-Z\W\d_]) : lookahead for uppercaseLetter || specialChar || number
karthik manchala
  • 13,492
  • 1
  • 31
  • 55
2

I'd use a single match expression per character class and then use standard boolean expressions to combine them:

var upper   = Regex.IsMatch(password, @".*[A-Z].*");
var lower   = Regex.IsMatch(password, @".*[a-z].*");
var digit   = Regex.IsMatch(password, @".*\d.*");
var special = Regex.IsMatch(password, @".*[\W_].*");

var passwordAccepted = lower && (upper || special || digit);

Which also allows you to give the user feedback why his password was rejected:

if(!digit)
{
    Console.Writeline("password must contain a number!")
}
...
3dGrabber
  • 4,710
  • 1
  • 34
  • 42