简体   繁体   中英

Design pattern to evaluate a boolean expression

Is there a common/defined design pattern which will help program an evaluator for boolean expressions.

I am writing a string matching algorithm for such expressions and looking for a design pattern which will help structure the algorithm.

Sample Expected Strings -

"nike AND (tshirt OR jerseys OR jersey OR tshirts OR (t AND shirt)) AND black" 

Your expression is in the infix notation . To evaluate it, convert it to the postfix notation .

Infix expression looks like:

<operand><operator><operand>

Postfix expression looks like:

<operand><operand><operator>

You can convert your expression using Shunting Yard Algorithm .

As the expression is converted, evaluate it using this approach (pseudocode):

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

I don't know of a design pattern per se which would fit your problem, but if your programming language has regex support, we can easily enough write a pattern such as this:

(?=.*\bnike\b)(?=.*\b(?:tshirts?|jerseys?|t\b.*\bshirt|shirt\b.*\bt))(?=.*\bblack\b).*

The pattern can be explained as:

(?=.*\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

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM