2009-10-06 64 views
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成功解析。

+1

JavaTokenParsers標識符和關鍵字之間沒有區別。我認爲agilefall的答案就是你需要的。 – 2009-10-07 00:53:54

回答

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

+0

謝謝。你已經明智地使用了交流管。 – 2009-10-07 16:24:37

相關問題