Parboiled - 如何解析实数?

时间:2016-05-06 11:52:00

标签: scala parboiled

我从一个声称解析实数的项目中得到了这个,但它以某种方式吃掉了小数点前部分:

object Main extends App {
  import org.parboiled.scala._

  val res = TestParser.parseDouble("2.3")
  println(s"RESULT: ${res.result}")

  object TestParser extends Parser {
    def RealNumber = rule { 
      oneOrMore(Digit) ~ optional( "." ~ oneOrMore(Digit) ) ~> { s =>
        println(s"CAPTURED '$s'")
        s.toDouble
      }
    }
    def Digit = rule { "0" - "9" }

    def parseDouble(input: String): ParsingResult[Double] =
      ReportingParseRunner(RealNumber).run(input)
  }
}

打印:

CAPTURED '.3'
RESULT: Some(0.3)

这里有什么问题?请注意,目前我不能从Parboiled-1转到Parboiled-2,因为我有一个更大的语法,必须重写。

2 个答案:

答案 0 :(得分:2)

parboiled documentation中所述,~>等行为规则会将紧接在同行规则之前的匹配。在规则序列oneOrMore(Digit) ~ optional( "." ~ oneOrMore(Digit) )中,紧接在前的规则为optional( "." ~ oneOrMore(Digit) ),因此您只能在操作规则中获得匹配".3"

为了解决这个问题,您可以将前两个元素提取到一个单独的规则中:

def RealNumberString = rule { 
  oneOrMore(Digit) ~ optional( "." ~ oneOrMore(Digit) ) 
}

def RealNumber = rule {
  RealNumberString ~> { s =>
    println(s"CAPTURED '$s'")
    s.toDouble
  }
}

或者将两个部分推到堆叠上,然后将它们组合起来:

def RealNumber = rule {
  oneOrMore(Digit) ~> identity ~ 
  optional( "." ~ oneOrMore(Digit) ) ~> identity ~~> { (s1, s2) =>
    val s = s1 + s2
    println(s"CAPTURED '$s'")
    s.toDouble
  }
}

答案 1 :(得分:0)

这是一个解决方案,但它看起来非常难看。可能有更好的方法:

def Decimal = rule {
  Integer ~ optional[Int]("." ~ PosInteger) ~~> { (a: Int, bOpt: Option[Int]) =>
    bOpt.fold(a.toDouble)(b => s"$a.$b".toDouble) /* ??? */
}}
def PosInteger  = rule { Digits ~> (_.toInt) }
def Integer     = rule { optional[Unit]("-" ~> (_ => ())) /* ??? */ ~
  PosInteger ~~> { (neg: Option[Unit], num: Int) =>
    if (neg.isDefined) -num else num
  }
}
def Digit       = rule { "0" - "9" }
def Digits      = rule { oneOrMore(Digit) }

def parseDouble(input: String): ParsingResult[Double] =
  ReportingParseRunner(Decimal).run(input)