[英]Design pattern to evaluate a boolean expression
是否有一个通用/定义的设计模式可以帮助为布尔表达式编写一个评估器。
我正在为此类表达式编写字符串匹配算法,并寻找有助于构建算法的设计模式。
示例预期字符串 -
"nike AND (tshirt OR jerseys OR jersey OR tshirts OR (t AND shirt)) AND black"
您的表达式采用中缀表示法。 要评估它,请将其转换为后缀表示法。
中缀表达式如下所示:
<operand><operator><operand>
后缀表达式如下所示:
<operand><operand><operator>
您可以使用Shunting Yard Algorithm转换您的表达式。
在转换表达式时,使用以下方法(伪代码)对其进行评估:
Begin
for each character ch in the postfix expression, do
if ch is an operator ⨀ , then
a := pop first element from stack
b := pop second element from the stack
res := b ⨀ a
push res into the stack
else if ch is an operand, then
add ch into the stack
done
return element of stack top
End
我不知道适合您问题的设计模式本身,但如果您的编程语言支持正则表达式,我们可以轻松地编写这样的模式:
(?=.*\bnike\b)(?=.*\b(?:tshirts?|jerseys?|t\b.*\bshirt|shirt\b.*\bt))(?=.*\bblack\b).*
该模式可以解释为:
(?=.*\bnike\b) match "nike" AND
(?=.*\b(?:tshirts?|jerseys?|t\b.*\bshirt|shirt\b.*\bt))
match tshirt(s), jersey(s) or "t" and "shirt" AND
(?=.*\bblack\b) match "black"
.* then consume the entire line
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.