using regex for math expressions in java?

前端 未结 1 1592
北恋
北恋 2020-12-22 07:56

I am working on this regex

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

I need this

相关标签:
1条回答
  • 2020-12-22 08:39

    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.

    0 讨论(0)
提交回复
热议问题