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

2024-09-28 01:30:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我不熟悉regex。我使用的是python2.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)

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


Tags: italllengthregexexpressiontrycombshould
1条回答
网友
1楼 · 发布于 2024-09-28 01:30:56

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

如果您的目标是解释正则表达式并生成每个案例。。。这很难,你应该解释为什么?在我们更进一步之前。在

如果你只想得到字母组合:

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替换为任意系列的字符。在

相关问题 更多 >

    热门问题