# How to allow optional outermost parenthesis?

I am writing a parser for certain expressions. I want to allow parentheses to be optional at the outermost level. My current parser looks like this:

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

As it is, this parser accepts only fully parenthesized expressions, such as:

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

My question is, is there any modification I can make to this parser in order for the outermost parenthesis to be optional? I would like to accept the string:

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

Thanks!

## Answers

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 }