假设我在组合器解析器中表达了一种含糊不清的语言。有没有办法让某些表达在当地贪婪?这是我的意思的一个例子。
import scala.util.parsing.combinator._
object Example extends JavaTokenParsers {
def obj: Parser[Any] = (shortchain | longchain) ~ anyrep
def longchain: Parser[Any] = zero~zero~one~one
def shortchain: Parser[Any] = zero~zero
def anyrep: Parser[Any] = rep(any)
def any: Parser[Any] = zero | one
def zero: Parser[Any] = "0"
def one: Parser[Any] = "1"
def main(args: Array[String]) {
println(parseAll(obj, args(0) ))
}
}
编译完成后,我可以按如下方式运行它:
$ scala Example 001111
[1.7] parsed: ((0~0)~List(1, 1, 1, 1))
我想以某种方式指示obj
的第一部分在本地贪婪并与longchain
匹配。如果我切换订单,它会匹配longchain
,但这不是因为贪婪。
def obj: Parser[Any] = (longchain | shortchain) ~ anyrep
答案 0 :(得分:14)
使用|||
:
object Example extends JavaTokenParsers {
def obj: Parser[Any] = (shortchain ||| longchain) ~ anyrep
def longchain: Parser[Any] = zero~zero~one~one
def shortchain: Parser[Any] = zero~zero
def anyrep: Parser[Any] = rep(any)
def any: Parser[Any] = zero | one
def zero: Parser[Any] = "0"
def one: Parser[Any] = "1"
def main(args: Array[String]) {
println(parseAll(obj, args(0) ))
}
}
scala> Example.main(Array("001111"))
[1.7] parsed: ((((0~0)~1)~1)~List(1, 1))