简体   繁体   中英

using regex for math expressions in java?

I am working on this regex

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM