I would like to know if its somehow possible to return a single random character from a regex pattern, written in short term.
So here is my case..
I have created some Regex patterns contained in an Enum:
import random
from _operator import invert
from enum import Enum
import re
class RegexExpression(Enum):
LOWERCASE = re.compile('a-z')
UPPERCASE = re.compile('A-Z')
DIGIT = re.compile('\d')
SYMBOLS = re.compile('\W')
I want for these to be returned as a string containing all the characters that the regex expresses, based on this method below:
def create_password(symbol_count, digit_count, lowercase_count, uppercase_count):
pwd = ""
for i in range(1, symbol_count):
pwd.join(random.choice(invert(RegexExpression.SYMBOLS.value)))
for i in range(1, digit_count):
pwd.join(random.choice(invert(RegexExpression.DIGIT.value)))
for i in range(1, lowercase_count):
pwd.join(random.choice(invert(RegexExpression.LOWERCASE.value)))
for i in range(1, uppercase_count):
pwd.join(random.choice(invert(RegexExpression.UPPERCASE.value)))
return pwd
I have tried several thing, but the only option I find possible is using an Enum containing long regex patterns, or strings like in the below example:
LOWERCASE = "abcdefghijklmnopqrstuvwxyz"
... And so on with the other variables in use.
Any suggestions or solutions to this scenario?
--EDIT--
Mad Physicist brought the solution for my issue - Thanks a lot! Here is the working code:
def generate_password(length):
tmp_length = length
a = random.randint(1, length - 3)
tmp_length -= a
b = random.randint(1, length - a - 2)
tmp_length -= b
c = random.randint(1, length - a - b - 1)
tmp_length -= c
d = tmp_length
pwd = ""
for i in range(0, a):
pwd += random.choice(string.ascii_lowercase)
for i in range(0, b):
pwd += random.choice(string.ascii_uppercase)
for i in range(0, c):
pwd += random.choice(string.digits)
for i in range(0, d):
pwd += random.choice(string.punctuation)
pwd = ''.join(random.sample(pwd, len(pwd)))
return pwd