python - 如何从正则表达式模式返回随机字符?蟒蛇 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
解决方案
该string
模块具有您想要的所有定义。
- 而不是
RegexExpression.LOWERCASE
使用string.ascii_lowercase
- 而不是
RegexExpression.UPPERCASE
使用string.ascii_uppercase
- 而不是
RegexExpression.DIGIT
使用string.digits
RegexExpression.SYMBOLS
可能最接近string.punctuation
RegEx 并不真正适合这项任务。表达式用于检查字符是否属于某个类。我不知道在不了解源代码/实现细节的情况下检查字符类规范的好方法。
推荐阅读
- kubernetes - 有没有办法阻止特使添加特定的标头?
- c++ - 这些浮点属性宏是 GCC 特有的吗?
- swift - Swift 数组地址与 &array[0] 不同
- matlab - matlab中的符号模运算
- javascript - 在 Laravel 中使用 vue.js 从谷歌位置自动完成获取纬度和经度
- javascript - 简而言之,如何实例化作为参数给出的不同函数
- delphi - 有没有办法在不包括原始文件的目录结构的情况下创建 TZipfile?
- hyperlink - 在雪花表字段中嵌入超链接
- html - flexbox中的大型primeng组件屠夫css
- arrays - char数组C末尾的奇怪字符