【问题标题】:parser combinator: how to terminate repetition on keyword解析器组合器:如何终止关键字的重复
【发布时间】:2009-10-06 22:00:37
【问题描述】:

我试图弄清楚如何使用关键字终止重复的单词。一个例子:

class CAQueryLanguage extends JavaTokenParsers {
    def expression = ("START" ~ words ~ "END") ^^ { x =>
        println("expression: " + x);
        x
    }
    def words = rep(word) ^^ { x =>
        println("words: " + x)
        x
    }
    def word = """\w+""".r
}

当我执行时

val caql = new CAQueryLanguage
caql.parseAll(caql.expression, "START one two END")

它打印出words: List(one, two, END),表明words 解析器已经消耗了我输入中的END 关键字,导致表达式解析器无法匹配。我希望END 不与words 匹配,这将允许expression 成功解析。

【问题讨论】:

  • JavaTokenParsers 不区分标识符和关键字。我认为 Agilefall 的答案正是您所需要的。

标签: parsing scala combinators


【解决方案1】:

这是你要找的吗?

import scala.util.parsing.combinator.syntactical._

object CAQuery extends StandardTokenParsers {
    lexical.reserved += ("START", "END")
    lexical.delimiters += (" ")

    def query:Parser[Any]= "START" ~> rep1(ident) <~ "END"

    def parse(s:String) = {
       val tokens = new lexical.Scanner(s)
       phrase(query)(tokens)
   }   
}

println(CAQuery.parse("""START a END"""))       //List(a)
println(CAQuery.parse("""START a b c END"""))   //List(a, b, c)

如果您想了解更多详情,可以查看this blog post

【讨论】:

  • 谢谢。您明智地使用了内胎。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-20
  • 1970-01-01
  • 1970-01-01
  • 2012-08-28
  • 2012-09-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多