如何允许可选的最外括号?

时间:2014-03-08 19:08:03

标签: scala parsing parser-combinators

我正在为某些表达式编写解析器。我想允许括号在最外层是可选的。我当前的解析器如下所示:

class MyParser extends JavaTokenParsers {

  def expr = andExpr | orExpr | term
  def andExpr = "(" ~> expr ~ "and" ~ expr <~ ")"
  def orExpr = "(" ~> expr ~ "or" ~ expr <~ ")"
  def term = """[a-z]""".r
}

实际上,此解析器仅接受完全带括号的表达式,例如:

val s1 = "(a and b)"
val s2 = "((a and b) or c)"
val s3 = "((a and b) or (c and d))"

我的问题是,为了使最外面的括号可选,我可以对此解析器进行任何修改吗?我想接受字符串:

val s4 = "(a and b) or (c and d)"

谢谢!

1 个答案:

答案 0 :(得分:2)

class MyParser extends JavaTokenParsers {
  // the complete parser can be either a parenthesisless "andExpr" or parenthesisless          
  // "orExpr " or "expr"
  def complete = andExpr | orExpr | expr
  def expr = parenthesis | term
  // moved the parenthesis from the andExpr and orExpr so I dont have to create
  // an extra parenthesisless andExpr and orExpr
  def parenthesis = "(" ~> (andExpr | orExpr) <~ ")"
  def andExpr = expr ~ "and" ~ expr
  def orExpr = expr ~ "or" ~ expr
  def term = """[a-z]""".r
}