Defining constraints in Z3 using Boolean operators

前端 未结 1 1494
借酒劲吻你
借酒劲吻你 2021-01-21 11:59

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 exampl

相关标签:
1条回答
  • 2021-01-21 12:33

    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
    
    0 讨论(0)
提交回复
热议问题