【发布时间】:2018-09-11 22:25:18
【问题描述】:
我想知道是否有可能从正则表达式模式中返回单个随机字符,用短期编写。
这就是我的情况..
我创建了一些包含在枚举中的正则表达式模式:
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
我已经尝试了几件事,但我发现唯一可能的选择是使用包含长正则表达式模式或字符串的枚举,如下例所示:
LOWERCASE = "abcdefghijklmnopqrstuvwxyz"
... 以此类推,其他变量正在使用中。
对这种情况有什么建议或解决方案吗?
--编辑--
Mad Physicist 为我的问题带来了解决方案 - 非常感谢! 这是工作代码:
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
【问题讨论】:
-
使用字符串模块?
-
点赞就好了。你现在得到了代表:)
-
另外,您的正则表达式有错误。我已经在第二个答案中解决了这个问题。
标签: python regex string design-patterns char