parser combinator:如何终止关键字的重复

时间:2009-10-06 22:00:37

标签: parsing scala combinators

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

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关键字,使表达式解析器无法匹配。我希望ENDwords不匹配,这将允许expression成功解析。

1 个答案:

答案 0 :(得分:4)

这是你在找什么?

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