在java中使用正则表达式的数学表达式? [英] using regex for math expressions in java?

查看:255
本文介绍了在java中使用正则表达式的数学表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用这个正则表达式

I am working on this regex

((([(]?[-]?[0-9]*[.]?[0-9]+)+([\/\+\-\*])+)+([0-9]*[.]?[0-9]+[)]?)+[\+\-\*\/]?([0-9]*)*)+

我需要这样接受任何表达式:(2 + 2 * 7)-4 + 2 /(5-3)+2

,我想避免这样的表达式:(2 + 3) - 或2 + 2-(2 + 3

I need this to accept any expression like: (2+2*7)-4+2/(5-3)+2
and I want to avoid expressions like: (2+3)- or 2+2-(2+3

目标是从用户获取表达式并将其分解为令牌,但在此之前,我想检查输入的有效性。

The goal is to get the expression from the user and break it down into tokens, but before doing that I want to check the validity of the input.

推荐答案

以最普遍的形式,正则表达式可以描述常规语言。另一方面,数学公式通常被形式化为无上下文的语言,它们是常规语言的超集。 Chomsky层次结构使这一点清楚:常规语言是类型3,而无上下文的是更普遍的类型2。

In their most general form, regular expressions can describe regular languages. On the other hand, math formulae are usually formalized as context-free languages, which are a superset of the regular languages. The Chomsky hierarchy make this distinction clear: regular languages are type 3, while context-free ones are of the more general type 2.

直观上,这里的关键区别在于常规语言不能计数,所以他们无法平衡打开和关闭括号。可以使用有限状态自动机来检测常规语言,但是仅使用有限数量的状态,因此可能无法跟踪到目前为止看到的开始圆括号数,因为可能会有任意数量的数字。

Intuitively, the key distinction here is that regular languages cannot count, so they cannot balance opening and closing parentheses. A regular language can be detected using a finite state automaton, but using only a finite number of states, you cannot possibly keep track of how many opening parentheses you have seen so far, since there might be an arbitrary number of them.

您可能需要调查词法分析器解析器。通常你会用正则表达式将你的流标记为数字,运算符和类似的东西,而你可以使用后者构建和检查由这些令牌组成的表达式。

You might want to investigate the distinction between a lexer and a parser. Usually you'd use the former, with regular expressions, to tokenize your streams into numbers, operators and the likes, while you'd use the latter to build and check expressions composed from these tokens.

这篇关于在java中使用正则表达式的数学表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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