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

<p>Basically </p>

<ul>
<li>nest parentheses is not allowed (meaning '(1+(2+3))
' will get rejected</li>
<li>after a bracket must come a number (or the expressions ends)</li>
</ul>

<p>Few examples for valid expressions:</p>

<pre><code>['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)']
</code></pre>

<p>Basically what I thought of doing is splitting the problem to</p>

<ol>
<li>an expression is inside brackets</li>
<li>an expression is not inside a brackets</li>
</ol>

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

<p>Im having troubles putting it all together tho...</p>

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

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

<p>It's a bit long but not complicated.</p>

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

python regex expression calculator