Scala:我可以推动组合器解析器变得局部贪婪吗?

发布于 2024-08-27 16:00:44 字数 794 浏览 12 评论 0原文

假设我有一种用组合器解析器表达的模糊语言。有没有办法让某些表达式局部贪婪?这是我的意思的一个例子。

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 匹配。如果我交换顺序,它会匹配长链,但这并不是因为贪婪。

def obj: Parser[Any] = (longchain | shortchain) ~ anyrep

Suppose I have an ambiguous language expressed in combinator parser. Is there a way to make certain expressions locally greedy? Here's an example of what I mean.

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) ))
  }
}

After compiling, I can run it as follows:

$ scala Example 001111
[1.7] parsed: ((0~0)~List(1, 1, 1, 1))

I would like to somehow instruct the first part of obj to be locally greedy and match with longchain. If I switch the order around, it matches the longchain, but that's not because of the greediness.

def obj: Parser[Any] = (longchain | shortchain) ~ anyrep

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

〗斷ホ乔殘χμё〖 2024-09-03 16:00:44

使用|||

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))

Use |||:

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))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文