danielzy danielzy - 3 months ago 28
Python Question

Regex for a calculator input

I'm trying to create a regular expression to decide if an input is a valid input for my very basic calculator.

Basically


  • nest parentheses is not allowed (meaning '(1+(2+3))
    ' will get rejected

  • after a bracket must come a number (or the expressions ends)



Few examples for valid expressions:

['1+19+2', '(5-06-9)/98*7', '(14/2-393+01)+3', '(00-0*7)', '(3*17-9+5-6)', '(6+1/6)+6/9', '(6/8)/2', '(6/1)', '(08+5+8)-7/19', '(9938/2)']


Basically what I thought of doing is splitting the problem to


  1. an expression is inside brackets

  2. an expression is not inside a brackets



And the regex will accept any thing that is
1[+-*/]2


Im having troubles putting it all together tho...

Answer

With re.match. The pattern structure is simple: operand (?: operator operand )*$ where operand can be a number or an expression between brackets. (Note that with re.match you don't need to anchor the pattern at the start of the string).Result:

 (?:[0-9]+|\([0-9]+(?:[-+*/][0-9]+)*\))(?:[-+*/](?:[0-9]+|\([0-9]+(?:[-+*/][0-9]+)*\)))*$
#^-------------operand----------------^         ^-------------operand----------------^

It's a bit long but not complicated.

Feel free to edit the pattern to support other kinds of numbers (decimal, relative, sci notation...)