Let's say, I want to restrict each character of the string to the charset: [a-zA-Z0-9_] using Z3 constraints, can I use a boolean operator to specify that?
As an example:
input = [BitVec("input%s" % i, 8) for i in range(10)]
for i in range(10):
s.add(input[i] >= 0x30 and input[i] <= 0x39)
s.add(input[i] >= 0x41 and input[i] <= 0x5A)
s.add(input[i] >= 0x61 and input[i] <= 0x7A)
Is this correct? Any other efficient way to define constraints?
Usually in Python, I could do something like:
import string
charset = string.uppercase + string.lowercase + string.digits + "_"
for i in charset:
...
Can something similar be done to define constraints in Z3?
Thanks.
The best way to go about this would be to simply use z3's regular-expression matching facilities:
from z3 import *
import string
lower = Union([Re(c) for c in string.lowercase])
upper = Union([Re(c) for c in string.uppercase])
digs = Union([Re(c) for c in string.digits])
uscore = Re('_')
charset = Union(lower, upper, digs, uscore)
lang = Plus(charset)
s = Solver()
test = String("test")
s.add(Length(test) == 10)
s.add(InRe(test, lang))
print s.check()
print s.model()
This prints:
sat
[test = "9L25ZPC1B8"]
Or you can use it to test whether particular strings belong to the regular-expression you've defined:
>>> print (simplify(InRe("hEllO_123", lang)))
True
>>> print (simplify(InRe("%$", lang)))
False
来源:https://stackoverflow.com/questions/53808101/defining-constraints-in-z3-using-boolean-operators