1

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!

4
  • Do you have to put all those conditions into a single regex? Or can you break it into one regex for each condition? Commented Nov 28, 2020 at 6:36
  • Are you trying to do it to check for password requirement? Commented Nov 28, 2020 at 6:38
  • @John Gordon Nope they don't all have to be in a single regex :) Commented Nov 28, 2020 at 6:41
  • @Pax yup! I am checking for password requirement Commented Nov 28, 2020 at 6:42

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

This is perfect! Only problem is it doesn't match if I have any lowercase characters in the string. Like for example the string "A00!$a" is supposed to match. Do you know what I can do to fix this?
@SegmentationFault You can add a-z to the matching character class, see regex101.com/r/5zbejo/1
2

This regex should work for you in python

^(?=.*[A-Z])(?=.*[0-9].*[0-9])(?=.*[!@#$%^&*()_+,.\\\/;':\"-].*[!@#$%^&*()_+,.\\\/;':\"-]).{6,8}$

Here is the test run in regex101

3 Comments

Thanks a lot, this works! except for a few things: 1. I just changed the end to .{6,8} (to allow lenghts between 6 and 8). 2. This expression requires that I have atleast one small character, which isnt part of the requirements. But this a great start I can probably figure it out! thanks!
Also I just noticed one more thing, it lets me put in as many special chars as I want whereas its only asking for exactly 2
@Segmentation Fault: Be aware that matches A12!!*$@, more than 2 special characters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.