Warm tip: This article is reproduced from serverfault.com, please click

Regex expression to check if string obeys certain conditions

发布于 2020-11-28 06:34:46

I need to write a python function that takes a string, and uses REGEX to check if the string contains:

  1. At least 1 uppercase letter;
  2. At least 2 numerical digits;
  3. Exactly 2 special characters, !@#$&*-_.
  4. A length of 6-8 characters;

Returns true if these exist and false otherwise. I'm good with the function, however, I'm having trouble with the regular expression.

What I have so far is: [A-Z]+\d{2,}[!@#\$&\*-_\.]{2}

I know this doesn't work, I'm really confused since I'm new to regex.

Thanks for your help!

Questioner
Segmentation Fault
Viewed
0
The fourth bird 2020-11-28 21:43:07

You can use

^(?=[^A-Z\r\n]*[A-Z])(?=[^\d\r\n]*\d[^\d\r\n]*\d)(?=.{6,8}$)[A-Z\d]*[!@#$&*_.-][A-Z\d]*[!@#$&*_.-][A-Z\d]*$

Note to escape the \- in the character class or place it at the start or end. Else it would denote a range.

Explanation

  • ^ Start of string
  • (?=[^A-Z\r\n]*[A-Z]) Positive lookahead, assert a char A-Z
  • (?=[^\d\r\n]*\d[^\d\r\n]*\d) Positive lookahead, assert 2 digits
  • (?=.{6,8}$) Positive lookahead, assert 6 - 8 characters in total
  • [A-Z\d]*[!@#$&*_.-][A-Z\d]*[!@#$&*_.-][A-Z\d]* Match 2 "special" characters
  • $ End of string (Or use \Z if there can no newline following)

Regex demo