如何在java中实现类似C的解析器
我需要将类似 C 的脚本(实际上是 Groovy)解析为几个部分,使用“(”、“)”、“&&”和“||”作为这样的分隔符:
从字符串中
(boo == 1 && (foo == null || foo == 0))
我需要得到某种像这样的列表
["boo == 1", "&&", ["foo == null", "||", "foo == 0"] ]
(list of 3 items, third one is a list too)
使用“foo == 1”条件看起来很简单,但它可以是“foo.item(2).contains('abcd')== true “也(条件也可以包含大括号),我坚持下去。
实现这样的解析器的最佳方法是什么?有什么有用的库或框架可以帮助我吗?对于我的情况,哪一个更容易?
I need to parse C-like scripts (actually Groovy) into several parts, using "(", ")", "&&" and "||" as delimiters like this:
From string
(boo == 1 && (foo == null || foo == 0))
I need to get some kind of List like this
["boo == 1", "&&", ["foo == null", "||", "foo == 0"] ]
(list of 3 items, third one is a list too)
With "foo == 1" condition it looks easy, but it can be "foo.item(2).contains('abcd') == true" also (condition can contain braces too), and I'm stuck with it.
What is the best way to implement such a parser? Are there any useful libraries or frameworks that can help me? And which one is easier in my case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实现此类解析器的最佳、最简洁的方法是使用 JavaCC 或 ANTLR 等解析器库。这样,您不仅可以获得一个列表,甚至还可以获得具有整个层次结构的完整语法树。
The best and cleanest way to implement such a parser goes through using a parser library like JavaCC or ANTLR. With this, you don't only get a list, but even a full syntax tree with entire hierarchy.