3

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

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成功解析。

4

1 回答 1

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)

如果您想了解更多详细信息,可以查看此博客文章

于 2009-10-07T00:42:04.873 回答