对 single/double 字符串引号进行 pyparsing 验证
pyparsing validation on single/double quotes on strings
我有一个公式格式是这样的:
lhs = pp.Word(pp.alphas + pp.alphas8bit + pp.alphanums + "." + "_")
rhs = (
pp.Optional(pp.oneOf("' \""))
+ pp.Word(pp.alphas + pp.alphas8bit + pp.alphanums + "." + "_" + "-" + ":")
+ pp.Optional(pp.oneOf("' \""))
)
expression = lhs + pp.oneOf("> < = >= <=") + rhs
所以,它工作正常:
>>> print(expression.parseString("name = 'user1'"))
>>> ['name', '=', "'", 'user1', "'"]
>>> print(expression.parseString('user.id >= 10'))
>>> ['user.id', '>=', '10']
但是,当 rhs
以 "
开头时,如何验证它也必须以 "
(双引号)结束,'
也是如此(单引号)。此外,当输入以其中的 none 开头(如 Integer)时,它也必须以其中的 none 结尾。但现在它从不验证它们:
>>> print(expression.parseString("name = \"user1'")) # invalid!
>>> ['name', '=', '"', 'user1', "'"]
>>> print(expression.parseString('user.id >= 10"')) # invalid!
>>> ['user.id', '>=', '10', '"']
那么,如何进行这样的验证?
试一试:
lhs = pp.Word(pp.alphas + pp.alphas8bit + pp.alphanums + "." + "_")
rhs_str = pp.Word(pp.alphas + pp.alphas8bit + pp.alphanums + "." + "_" + "-" + ":")
rhs_num = pp.Word(pp.nums)
rhs = (
(pp.Suppress('"') + rhs_str + pp.Suppress('"'))
^ (pp.Suppress("'") + rhs_str + pp.Suppress("'"))
^ (rhs_num)
)
expression = lhs + pp.oneOf("> < = >= <=") + rhs
我有一个公式格式是这样的:
lhs = pp.Word(pp.alphas + pp.alphas8bit + pp.alphanums + "." + "_")
rhs = (
pp.Optional(pp.oneOf("' \""))
+ pp.Word(pp.alphas + pp.alphas8bit + pp.alphanums + "." + "_" + "-" + ":")
+ pp.Optional(pp.oneOf("' \""))
)
expression = lhs + pp.oneOf("> < = >= <=") + rhs
所以,它工作正常:
>>> print(expression.parseString("name = 'user1'"))
>>> ['name', '=', "'", 'user1', "'"]
>>> print(expression.parseString('user.id >= 10'))
>>> ['user.id', '>=', '10']
但是,当 rhs
以 "
开头时,如何验证它也必须以 "
(双引号)结束,'
也是如此(单引号)。此外,当输入以其中的 none 开头(如 Integer)时,它也必须以其中的 none 结尾。但现在它从不验证它们:
>>> print(expression.parseString("name = \"user1'")) # invalid!
>>> ['name', '=', '"', 'user1', "'"]
>>> print(expression.parseString('user.id >= 10"')) # invalid!
>>> ['user.id', '>=', '10', '"']
那么,如何进行这样的验证?
试一试:
lhs = pp.Word(pp.alphas + pp.alphas8bit + pp.alphanums + "." + "_")
rhs_str = pp.Word(pp.alphas + pp.alphas8bit + pp.alphanums + "." + "_" + "-" + ":")
rhs_num = pp.Word(pp.nums)
rhs = (
(pp.Suppress('"') + rhs_str + pp.Suppress('"'))
^ (pp.Suppress("'") + rhs_str + pp.Suppress("'"))
^ (rhs_num)
)
expression = lhs + pp.oneOf("> < = >= <=") + rhs