解析器组合器:如何终止关键字重复

发布于 2024-08-07 12:53:57 字数 660 浏览 1 评论 0原文

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你另情深 2024-08-14 12:53:57

这是您要找的吗?

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)

如果您想了解更多详细信息,可以查看 这篇博文

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文