[英]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.