在您的第二个模式中,您可以将字符串^
的开头替换为custom/restricted个^(?!(.{15}|.{17})$)
(这是基于要排除的长度构建的).这将确保匹配字符串的每个开头,但前提是该字符串的长度不是15或17个字符.
Use ^(?!(.{15}|.{17})$)[0-9]{13,20}$
instead of ^[0-9]{13,20}$
下面是处理不同不连续范围的通用代码:
# feel free to adjust the values
(l, r), excep = [13, 20], [15, 17]
to_excl = "|".join(".{%s}" % n for n in excep)
pat = re.compile(r"^(?!(%s)$)[0-9]{%s,%s}$" % (to_excl, l, r))
测试/输出:
for t in text:
print(
f"{t:<22}", f"{len(t):<4}",
"match" if pat.match(t) else "no-match"
)
01234 5 no-match
012345678901234 15 no-match
0123456789012345 16 match
01234567890123456 17 no-match
012345678901234567 18 match
012345678901234567890 21 no-match
使用的输入:
from string import digits
s = digits; lens = [5, 15, 16, 17, 18, 21]
text = [s * (l // 10) + s[:l % 10] for l in lens]
['01234',
'012345678901234',
'0123456789012345',
'01234567890123456',
'012345678901234567',
'012345678901234567890']