user6882757
user6882757

Reputation:

Why my regex not working for char validation

Here my (?=.*[a-z]{2}) is explicitly checking for explicitly 2 small chars. but could not taking it

import re
char = 'Massas23#'
if re.search(r"^(?=.*[\d])(?=.*[A-Z])(?=.*[a-z]{2})(?=.*[@#$])[\w\d@#$]{6,12}$", char):
    print ("match")
else:
    print ("Not Match")

My out is Match and Expected is Not Match

Upvotes: 1

Views: 58

Answers (2)

Emma
Emma

Reputation: 27743

Maybe,

^(?!.*[a-z]{3})(?=.*[\d])(?=.*[A-Z])(?=.*[a-z]{2})(?=.*[@#$])[\w\d@#$]{6,12}$

might work then.

(?!.*[a-z]{3})

means more than three consecutive lowercases are not allowed.

Demo 1

Test

import re

char = 'Massas23#'

if re.search(r"^(?!.*[a-z]{3})(?=.*[\d])(?=.*[A-Z])(?=.*[a-z]{2})(?=.*[@#$])[\w\d@#$]{6,12}$", char):
    print("match")
else:
    print("Not Match")

If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here


I guess we were not trying to match MAsSa23#, if you wish to match that,

^(?!.*[a-z]{3})(?=.*[\d])(?=.*[A-Z])(?=.*[a-z]{1,2})(?=.*[@#$])[\w\d@#$]{6,12}$

would do that.

Demo 2

Upvotes: 1

The fourth bird
The fourth bird

Reputation: 163457

You could omit the lowercase chars from the character class and then match exactly 2 lowercase chars a-z.

You can make use of contrast using negated character classes for example matching not a digit.

^(?=.{6,12}$)(?=[^\d\s]*\d)(?=[^A-Z\s]*[A-Z])(?=[^@#$\s]*[@#$])[A-Z0-9_@#$]*[a-z][A-Z0-9_@#$]*[a-z][A-Z0-9_@#$]*$
  • ^ Start of string
  • (?=.{6,12}$) Assert 6 - 12 chars
  • (?=[^\d\s]*\d) Assert a digit
  • (?=[^A-Z\s]*[A-Z]) Assert an uppercase char
  • (?=[^@#$\s]*[@#$]) Assert a special char
  • [A-Z0-9_@#$]*[a-z][A-Z0-9_@#$]*[a-z][A-Z0-9_@#$]* Match 2 lowercase a-z
  • $ End of string

Regex demo

Note that

  • [\d] does not have to be between square brackets
  • [\w\d@#$] \w also matches \d so that can be omitted from the character class

Upvotes: 0

Related Questions