首页 > 解决方案 > 如何从正则表达式模式返回随机字符?蟒蛇 3

问题描述

我想知道是否有可能从正则表达式模式中返回单个随机字符,短期编写。

所以这是我的情况..

我创建了一些包含在枚举中的正则表达式模式:

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')

我希望这些作为包含正则表达式表达的所有字符的字符串返回,基于以下方法:

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

我已经尝试了几件事,但我发现唯一可能的选择是使用包含长正则表达式模式的 Enum 或以下示例中的字符串:

LOWERCASE = "abcdefghijklmnopqrstuvwxyz"

...等等与使用中的其他变量。

对这种情况有什么建议或解决方案吗?

- 编辑 -

疯狂的物理学家为我的问题带来了解决方案 - 非常感谢!这是工作代码:

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

标签: pythonregexstringdesign-patternschar

解决方案


string模块具有您想要的所有定义。

RegEx 并不真正适合这项任务。表达式用于检查字符是否属于某个类。我不知道在不了解源代码/实现细节的情况下检查字符类规范的好方法。


推荐阅读