[假设你需要这个,因为这是某些奇怪的第三方系统需要正则表达式]
新方法
越来越多地考虑到Frederik的评论,我越来越同意。即使输入字符串很长,正则表达式引擎也应该能够将其编译成紧凑的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在内的所有数字范围都可正常工作。一个草率的估算表明,1GB的内存大约是9位数的极限。如果只匹配少量这样大小的数字,则可以使用更大的数字。
旧方法
[再次更新以获得更短的结果-除了偶尔聚合\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
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)
while len(slo) < len(shi): slo = '0' + slo
l, h, n = int(slo[0]), int(shi[0]), len(slo)
if l == h:
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:
xlo = slo[1:] == replace(slo[1:], '0')
xhi = shi[1:] == replace(shi[1:], '9')
mlo = int(slo[0] + replace(slo[1:], '9'))
mhi = int(shi[0] + replace(shi[1:], '0'))
if xlo:
if xhi:
return digits(l, h) + repeat('\d', n-1)
else:
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:
return alt(prefix + regexp(lo, mlo), regexp(mlo+1, hi))
else:
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))
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)
函数生成一个匹配介于lo
和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的0-9的正则表达式。
输出是一些测试用例,显示了范围和正则表达式:
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个数字,因此运行需要一段时间。
表达式应该足够紧凑,以避免任何缓冲区限制(我猜最坏情况下的内存大小与最大数字位数的平方成正比)。
注:我使用的是Python 3,但我不认为这对结果有太大影响。
int(start_number) <= test_number <= (end_number)
- Srikar Appalarajuexpression
字符串被放入配置文件中,并由某些硬件/固件解析。我也希望有其他方法!:( - TC Fox