Python 所有组合的正则表达式迭代

Python regex iteration for all combinations

我是正则表达式的新手。我正在使用 Python 2.7 和 BeautifulSoup4。我想遍历特定的正则表达式。

所需输出:

length : 5 , expression : [a-zA-Z0-9!&#%@]

It should try all possible combinations e.g:
['aaaaa','aaaab','aaaac',...,'aaaaz','aaaaA',...,'aaaaZ','aaaa0','aaaa9','aaaa!','AAA!!']

Moreover this should be possible too. If the expression is orange\d{1}

['orangea','oranges']]

我试过这个:

 regexInput = "a-z0-9"
 #regexInput = "a-zA-Z0-9!@#$%^&"
 comb = itertools.permutations(regexInput,passLength)
 for x in comb:
    ''.join(x)

我意识到这是一种完全错误的方法,因为这些只是排列。请帮忙。抱歉解释不好,非常沮丧。

用于排列或组合的 Itertools 函数将一系列元素作为第一个参数。它无法为您生成系列(从 a-zabc...xyz)。幸运的是 string 提供了一些包含 a-zA-Z.

的常量,例如 ascii_letters

如果您的目标是解释正则表达式并生成每个案例,...这非常困难,您应该在我们继续之前解释为什么?

如果您只想获得字母组合:

import string
from itertools import combinations_with_replacement

result = combinations_with_replacement(string.ascii_letters, 5)

#comb = [''.join(n) for n in result] # warning, heavy processing

print [''.join(result.next()) for _ in range(10)]
# > ['aaaaa', 'aaaab', 'aaaac', 'aaaad', 'aaaae', 'aaaaf', 'aaaag', 'aaaah', 'aaaai', 'aaaaj']

您可以用任何字符系列替换 string.ascii_letters