Well, you could make use of the fact that Python's regex engine only allows fixed-length regular expressions in lookbehind assertions:
import re
regexes = [r".x{2}(abc|def)", # fixed
r"a|bc", # variable/finite
r"(.)\1", # fixed
r".{0,3}", # variable/finite
r".*"] # variable/infinite
for regex in regexes:
try:
r = re.compile("(?<=" + regex + ")")
except:
print("Not fixed length: {}".format(regex))
else:
print("Fixed length: {}".format(regex))
will output
Fixed length: .x{2}(abc|def)
Not fixed length: a|bc
Fixed length: (.)\1
Not fixed length: .{0,3}
Not fixed length: .*
I'm assuming that the regex itself is valid.
Now, how does Python know whether the regex is fixed-length or not? Just read the source - in sre_parse.py
, there is a method called getwidth()
that returns a tuple consisting of the lowest and the highest possible length, and if these are not equal in a lookbehind assertion, re.compile()
will raise an error. The getwidth()
method walks through the regex recursively:
def getwidth(self):
# determine the width (min, max) for this subpattern
if self.width:
return self.width
lo = hi = 0
UNITCODES = (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY)
REPEATCODES = (MIN_REPEAT, MAX_REPEAT)
for op, av in self.data:
if op is BRANCH:
i = sys.maxsize
j = 0
for av in av[1]:
l, h = av.getwidth()
i = min(i, l)
j = max(j, h)
lo = lo + i
hi = hi + j
elif op is CALL:
i, j = av.getwidth()
lo = lo + i
hi = hi + j
elif op is SUBPATTERN:
i, j = av[1].getwidth()
lo = lo + i
hi = hi + j
elif op in REPEATCODES:
i, j = av[2].getwidth()
lo = lo + int(i) * av[0]
hi = hi + int(j) * av[1]
elif op in UNITCODES:
lo = lo + 1
hi = hi + 1
elif op == SUCCESS:
break
self.width = int(min(lo, sys.maxsize)), int(min(hi, sys.maxsize))
return self.width