How to write an Scala parser for arithmetic operations including string?

1.5k Views Asked by At

I am trying to use Scala Combinator-Parsing to parse and arithmetic operation in which at least one of the variables is string. I am a beginner in scala and I like this feature of it! For instance I wanna parse:
(number + 2) * 4

It has a good example of parsing numbers (float and integer with parenthesis) like:

  class Arith extends JavaTokenParsers {  
      def expr: Parser[Any] = term~rep("+"~term | "-"~term)
      def term: Parser[Any] = factor~rep("*"~factor | "/"~factor)
      def factor: Parser[Any] = floatingPointNumber | "("~expr~")"
    } 

and this one for string:

       object MyParsers extends RegexParsers {
        val ident: Parser[String] = """[a-zA-Z_]\w*""".r
       }

how can I change the first part to parse string beside numbers?

1

There are 1 best solutions below

2
On BEST ANSWER

I think you should add it to the factor alternatives:

def factor: Parser[Any] = ident | floatingPointNumber | "("~expr~")"