Trying to cope with following syntax (see 12.1 Format):
Reply syntax:
[<argument>[{SP<argument>}]"="]<value>LF
Multi-line reply syntax:
{[<argument>[{SP<argument>}]"="]<value>SP LF}
[<argument>[{SP<argument>}]"="]<value>LF for the last line!
This is my code:
import scala.util.parsing.combinator._
case class Result(argument: String, value: Float)
class ReplyParser extends RegexParsers{
override def skipWhitespace = false
private def floatingPointNumber: Parser[String] =
"""(-|\+)?(\d+(\.\d*)?|\d*\.\d+)""".r
private def value: Parser[Float] = floatingPointNumber ^^ (_.toFloat)
private def argument: Parser[String] = "[^= \n]+".r
private def arguments: Parser[List[String]] = rep1sep(argument," ") <~ "="
private def result: Parser[List[Result]] = arguments.? ~ value ^^ {
case arguments ~ value =>
arguments.getOrElse(List("")).map {
Result(_,value)
}
}
def reply: Parser[List[Result]] = rep1sep(result, " \n".r) <~ " " ^^ {
case result => result.flatten
}
}
object Parsing extends ReplyParser {
def main(args: Array[String]) {
val result = parseAll(reply,"a=+000.123 \nc d=-999.567 \n789 ")
println(s"$result")
}
}