[假设你需要这个,因为它的一些奇怪的第三方系统,需要正则表达式]
新方法
我越去想弗雷德里克评论,我越是同意。即使输入字符串很长,正则表达式引擎也应该能够将其编译为紧凑的DFA。许多情况下,下面是一个明智的解决办法:
import re
def regexp(lo, hi):
fmt = '%%0%dd' % len(str(hi))
return re.compile('(%s)' % '|'.join(fmt % i for i in range(lo, hi+1)))
(它工作正常,在下文的测试中所有的数值范围,包括99519000 - 99519099.粗糙背的最粗略计算表明,9这个数字大约是1GB内存的限制,这就是说,如果大多数数字的大小都匹配,如果只有少数匹配,则可以大得多)。
老方法
[再次更新给予更短的结果 - 从合并偶尔\d\d
这是关于好,因为产生的手分开]
假设所有的数字都是一样的长度(即你零垫左侧如果必要的话),这个工程:
import re
def alt(*args):
'''format regexp alternatives'''
if len(args) == 1: return args[0]
else: return '(%s)' % '|'.join(args)
def replace(s, c):
'''replace all characters in a string with a different character'''
return ''.join(map(lambda x: c, s))
def repeat(s, n):
'''format a regexp repeat'''
if n == 0: return ''
elif n == 1: return s
else: return '%s{%d}' % (s, n)
def digits(lo, hi):
'''format a regexp digit range'''
if lo == 0 and hi == 9: return r'\d'
elif lo == hi: return str(lo)
else: return '[%d-%d]' % (lo, hi)
def trace(f):
'''for debugging'''
def wrapped(lo, hi):
result = f(lo, hi)
print(lo, hi, result)
return result
return wrapped
#@trace # uncomment to get calls traced to stdout (explains recursion when bug hunting)
def regexp(lo, hi):
'''generate a regexp that matches integers from lo to hi only.
assumes that inputs are zero-padded to the length of hi (like phone numbers).
you probably want to surround with^and $ before using.'''
assert lo <= hi
assert lo >= 0
slo, shi = str(lo), str(hi)
# zero-pad to same length
while len(slo) < len(shi): slo = '0' + slo
# first digits and length
l, h, n = int(slo[0]), int(shi[0]), len(slo)
if l == h:
# extract common prefix
common = ''
while slo and slo[0] == shi[0]:
common += slo[0]
slo, shi = slo[1:], shi[1:]
if slo: return common + regexp(int(slo), int(shi))
else: return common
else:
# the core of the routine.
# split into 'complete blocks' like 200-599 and 'edge cases' like 123-199
# and handle each separately.
# are these complete blocks?
xlo = slo[1:] == replace(slo[1:], '0')
xhi = shi[1:] == replace(shi[1:], '9')
# edges of possible complete blocks
mlo = int(slo[0] + replace(slo[1:], '9'))
mhi = int(shi[0] + replace(shi[1:], '0'))
if xlo:
if xhi:
# complete block on both sides
# this is where single digits are finally handled, too.
return digits(l, h) + repeat('\d', n-1)
else:
# complete block to mhi, plus extra on hi side
prefix = '' if l or h-1 else '0'
return alt(prefix + regexp(lo, mhi-1), regexp(mhi, hi))
else:
prefix = '' if l else '0'
if xhi:
# complete block on hi side plus extra on lo
return alt(prefix + regexp(lo, mlo), regexp(mlo+1, hi))
else:
# neither side complete, so add extra on both sides
# (and maybe a complete block in the middle, if room)
if mlo + 1 == mhi:
return alt(prefix + regexp(lo, mlo), regexp(mhi, hi))
else:
return alt(prefix + regexp(lo, mlo), regexp(mlo+1, mhi-1), regexp(mhi, hi))
# test a bunch of different ranges
for (lo, hi) in [(0, 0), (0, 1), (0, 2), (0, 9), (0, 10), (0, 11), (0, 101),
(1, 1), (1, 2), (1, 9), (1, 10), (1, 11), (1, 101),
(0, 123), (111, 123), (123, 222), (123, 333), (123, 444),
(0, 321), (111, 321), (222, 321), (321, 333), (321, 444),
(123, 321), (111, 121), (121, 222), (1234, 4321), (0, 999),
(99519000, 99519099)]:
fmt = '%%0%dd' % len(str(hi))
rx = regexp(lo, hi)
print('%4s - %-4s %s' % (fmt % lo, fmt % hi, rx))
m = re.compile('^%s$' % rx)
for i in range(0, 1+int(replace(str(hi), '9'))):
if m.match(fmt % i):
assert lo <= i <= hi, i
else:
assert i < lo or i > hi, i
功能regexp(lo, hi)
建立该0123893887620之间的匹配值的正则表达式和hi
(零填充到最大长度)。您可能需要在之前放置一个^
,然后在$
之后(如在测试代码中)强制匹配成为整个字符串。
该算法实际上很简单 - 它递归地将事物分成普通前缀和“完整块”。一个完整的块是类似于200-599并且可以可靠匹配(在这种情况下与[2-5]\d{2}
)。
因此123-599分为123-199和200-599。后半部分是一个完整的块,前半部分具有共同的前缀1和23-99,它被递归地处理为23-29(通用前缀)和30-99(完整块)(并且我们最终终止,因为参数到每个呼叫都比初始输入短)。
唯一讨厌的细节是prefix
,这是必须的,因为参数regexp()
是整数,称为所以当产生,比方说,对于00-09的正则表达式,它实际上产生了0-9的正则表达式,而不领先0
输出是一串的测试用例,示出了范围和正则表达式:
0 - 0 0
0 - 1 [0-1]
0 - 2 [0-2]
0 - 9 \d
00 - 10 (0\d|10)
00 - 11 (0\d|1[0-1])
000 - 101 (0\d\d|10[0-1])
1 - 1 1
1 - 2 [1-2]
1 - 9 [1-9]
01 - 10 (0[1-9]|10)
01 - 11 (0[1-9]|1[0-1])
001 - 101 (0(0[1-9]|[1-9]\d)|10[0-1])
000 - 123 (0\d\d|1([0-1]\d|2[0-3]))
111 - 123 1(1[1-9]|2[0-3])
123 - 222 (1(2[3-9]|[3-9]\d)|2([0-1]\d|2[0-2]))
123 - 333 (1(2[3-9]|[3-9]\d)|2\d\d|3([0-2]\d|3[0-3]))
123 - 444 (1(2[3-9]|[3-9]\d)|[2-3]\d{2}|4([0-3]\d|4[0-4]))
000 - 321 ([0-2]\d{2}|3([0-1]\d|2[0-1]))
111 - 321 (1(1[1-9]|[2-9]\d)|2\d\d|3([0-1]\d|2[0-1]))
222 - 321 (2(2[2-9]|[3-9]\d)|3([0-1]\d|2[0-1]))
321 - 333 3(2[1-9]|3[0-3])
321 - 444 (3(2[1-9]|[3-9]\d)|4([0-3]\d|4[0-4]))
123 - 321 (1(2[3-9]|[3-9]\d)|2\d\d|3([0-1]\d|2[0-1]))
111 - 121 1(1[1-9]|2[0-1])
121 - 222 (1(2[1-9]|[3-9]\d)|2([0-1]\d|2[0-2]))
1234 - 4321 (1(2(3[4-9]|[4-9]\d)|[3-9]\d{2})|[2-3]\d{3}|4([0-2]\d{2}|3([0-1]\d|2[0-1])))
000 - 999 \d\d{2}
99519000 - 99519099 995190\d\d
它需要一段时间来运行作为最后的测试遍历99999999号。
表达式应该足够紧凑,以避免任何缓冲区限制(我猜想内存大小最坏的情况是成正比的最大数字的位数的平方)。
ps我使用python 3,但我不认为它在这里有很大的不同。
为什么不匹配正确的数字位数('\ d {8}'),然后对于在int中转换的所有匹配项,检查它是否在范围内? – Scharron
addint to @rnbcoder写道你不能把str转换为int并比较? 'int(start_number)<= test_number <=(end_number)' –
是否有任何理由必须用正则表达式来完成?我只是将该数字转换为一个int,并检查它是否在start_number和end_number之间。这可能效率稍低,但复杂性的顺序是相同的,因为检查正则表达式匹配是O(n),并且将字符串转换为int是O(n),那么两个int比较是O(1)。 –