简体   繁体   English

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

[英]parser combinator: how to terminate repetition on keyword

I'm trying to figure out how to terminate a repetition of words using a keyword. 我想弄清楚如何使用关键字终止重复的单词。 An example: 一个例子:

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
}

When I execute 当我执行

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

It prints words: List(one, two, END) , indicating the words parser has consumed the END keyword in my input, leaving the expression parser unable to match. 它打印words: List(one, two, END) ,表示words解析器在我的输入中使用了END关键字,使表达式解析器无法匹配。 I would like END to not be matched by words , which will allow expression to successfully parse. 我希望END不与words匹配,这将允许expression成功解析。

Is this what you are looking for? 这是你想要的?

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)

If you would like more details, you can check out this blog post 如果您想了解更多详情,可以查看此博文

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM