简体   繁体   English

计算布尔表达式的设计模式

[英]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 .您可以使用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演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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