解析器组合器:如何终止关键字的重复 [英] parser combinator: how to terminate repetition on keyword

查看:89
本文介绍了解析器组合器:如何终止关键字的重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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
}

执行时

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

它显示words: List(one, two, END),表明words解析器已在我的输入中使用了END关键字,从而使表达式解析器无法匹配.我希望ENDwords不匹配,这将允许expression成功解析.

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. I would like END to not be matched by words, which will allow expression to successfully parse.

推荐答案

这是您要寻找的吗?

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

这篇关于解析器组合器:如何终止关键字的重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆