我试图使用正则表达式作为输入,并从中生成正则表达式将匹配的所有可能值。
例如,如果regex是“以a开头、以c结尾的三个字母单词”,那么代码将生成一个值为[aac、abc、acc、adc、a1c….]的列表。
有什么简单的方法可以做到这一点吗?我在用蟒蛇。
最佳答案
这里有一个蛮力解决方案,应该有效。它的运行时间是O(L^max_length)(其中L是字母表的大小),因此使用它的风险自负。
def all_matching_strings(alphabet, max_length, regex):
"""Find the list of all strings over 'alphabet' of length up to 'max_length' that match 'regex'"""
if max_length == 0: return
L = len(alphabet)
for N in range(1, max_length+1):
indices = [0]*N
for z in xrange(L**N):
r = ''.join(alphabet[i] for i in indices)
if regex.match(r):
yield(r)
i = 0
indices[i] += 1
while (i<N) and (indices[i]==L):
indices[i] = 0
i += 1
if i<N: indices[i] += 1
return
示例用法:
alphabet = 'abcdef1234567890'
import re
regex = re.compile('f*[1-3]+$')
for r in all_matching_strings(alphabet, 5, regex):
print r
它将输出最长为5的所有字符串,从一个f的序列开始,然后是一个1-3的非空序列,然后结束:
1
2
3
f1
11
21
31
f2
12
22
32
f3
13
23
33
ff1
[more output omitted...]