mardi 11 septembre 2018

How to return a random character from a regex pattern? python 3

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?

Regards Kalrin

Aucun commentaire:

Enregistrer un commentaire