用于解析嵌套表达式的java方法 [英] java method for parsing nested expressions

查看:513
本文介绍了用于解析嵌套表达式的java方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我已经编写了一个函数来评估一个简单的数学运算,并且我在字符串中有一些用户输入,例如:
1 + [2 + [3 + 4]]
如何解析这些方括号并首先提取最内层文本(3 + 4),对其进行求值,然后解析外括号(2 + 7)?
我对正则表达式搜索和替换有基本的了解,但我知道他们不会像这样做递归。
我想要一些基本的java代码来做这件事,如果我能避免的话,还不是另一个jar / API。

lets say I've written a function to evaluate a simple mathematical operation, and I have some user input in a string such as: "1 + [2 + [3+4]]" How can I parse these square brackets and extract first the inner-most text (3+4), evaluate it, then parse the outer braces (2 + 7)? I have a rudimentary understanding of Regex search and replace, but I know they won't do recursion like this. I'd like some basic java code to do this, not yet another jar/API if I can avoid it.

推荐答案

实现目标的最简洁方法是为此目的编写Lexer和Parser。编写递归下降解析器对于算术表达式来说从头开始并不难。

The cleanest way to accomplish your goal is to write a Lexer and a Parser for this purpose. Writing a recursive descent parser is not that hard to do from scratch for arithmetic expressions.

网上有很多代码示例。 这是您的一个示例可以用来获取灵感。

There are numerous code examples on the web. This is an example that you could use for inspiration.

Lexer可以将您的输入标准化并将其抽象为令牌流。这样,你的Parser只需要处理令牌,而不必另外处理空白问题和其他讨厌的事情。

The Lexer is there to normalize your input and to abstract it to a stream of tokens. This way, your Parser only needs to work on tokens instead of additionally having to deal with whitespace issues and other annoying things.

两个 示例,用于基于堆栈的高级算法,显示递归下降方法的另一个示例

Two examples for high-level algorithms that are stack-based, another example that shows a recursive descent approach.

这篇关于用于解析嵌套表达式的java方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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