Regex calculator

I created a regex :

((\(\s*)          #match start parens
|(\d+\.?\d*)      #match a number
|([+-/%^!])       #match operators
|([*])            #match the asterisk operator
|(\s*\)))+        #match the end parens

which must share the parentheses, the number (whole numbers and decimal numbers ( 3and 6.28)) and operators ( +-/*^%!). I tried several tests

( (2 3 +) 6.28 +)  
(3.14 6.28 +)
( (3 4 +) (5 6 +) *)

and I noticed a few things. When I run a regular expression in expressions with two leading pairs, it seems to ignore one of the parentheses, and testing on the site seems to lead to many instances of null and repeat characters. Is there a way to map a valid expression and assign it to my own group? For example, if I have a phrase ( (2 3 +) 6.28 +)generated by the group will be: [ (, (, 2, 3, +, 6.28, +, )]?

, , python, . - (?.) (.?) . , . , . .

0
1

RPN, , RPN. , (Perl, PCRE, Python regex), :

  • , .
  • , , , .

RPN

^(\((?![ ]*[+/*-])(?:[ ]*|[+/*-](?![ ]*[+/*-])|(?:[ ]*\d+)?[ ]*\d+[ ]*[+/*-](?![ ]*[+/*-])[ ]*|(?1))*\))

demo , , " ", .

Non-RPN

^(\((?![*\/])(?:\d++|[+*\/-](?![+*\/-])|(?1))*(?<![+*\/-])\))

demo , , " ", .

  • , , , , . . , , .:)
  • - , , .
  • RPN ( ): -1*
  • , -RPN, , .

, .

^\s*-?\d+(?:\s*[-+*/]\s*\d+\s*)+$
+2

Source: https://habr.com/ru/post/1570226/


All Articles