带有嵌套括号的 scala 解析
尝试解析嵌套表达式,例如 GroupParser.parse("{{a}{{c}{d}}}") 经过几个小时后,我现在有了以下可以很好地解析 {a} 的片段,但失败并有
[1.5] failure: ``}'' expected but `{' found
{{a}{{b}{c}}}
^
sealed abstract class Expr
case class ValueNode(value:String) extends Expr
object GroupParser extends StandardTokenParsers {
lexical.delimiters ++= List("{","}")
def vstring = ident ^^ { case s => ValueNode(s) }
def expr = ( vstring | parens )
def parens:Parser[Expr] = "{" ~> expr <~ "}"
def parse(s:String) = {
val tokens = new lexical.Scanner(s)
phrase(expr)(tokens)
}
}
任何提示吗?
Trying to parse an nested expressions like GroupParser.parse("{{a}{{c}{d}}}")
After many hours i have now following snipplet that parse {a} well, but fails with
[1.5] failure: ``}'' expected but `{' found
{{a}{{b}{c}}}
^
sealed abstract class Expr
case class ValueNode(value:String) extends Expr
object GroupParser extends StandardTokenParsers {
lexical.delimiters ++= List("{","}")
def vstring = ident ^^ { case s => ValueNode(s) }
def expr = ( vstring | parens )
def parens:Parser[Expr] = "{" ~> expr <~ "}"
def parse(s:String) = {
val tokens = new lexical.Scanner(s)
phrase(expr)(tokens)
}
}
any hints?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题不在于嵌套,而在于排序。您的语法允许在花括号内任意嵌套表达式,但并没有说可以对表达式进行排序,因此解析器无法处理紧随其后的 {a} {{b}{c}}。您可以在语法中使用显式递归或使用 http://www.scala-lang.org/api/current/scala/util/parsing/combinator/Parsers.html
The problem isn't nesting, it's sequencing. Your grammar would allow arbitrary nesting of expressions inside curlies, but doesn't say that an expression can be sequenced so the parser can't handle {a} followed immediately by {{b}{c}}. You can code sequencing using explicit recursion in your grammar or by using one of the rep variants in http://www.scala-lang.org/api/current/scala/util/parsing/combinator/Parsers.html
表达式可以重复多次吗?如果是这样,这将起作用:
但是,尚不清楚您的语法是什么,或者为什么您的示例可以接受。
Can expressions be repeated multiple times? If so, this would work:
However, it is not clear what is your grammar, or why would your example be acceptable.
这会解析您给出的两个示例:
并成功输出:
This parses the two examples you gave:
And succeeds with output: