Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You could try something like this:</p> <pre><code>function validateInfix(infix) { var balance = 0; // remove white spaces to simplify regex infix = infix.replace(/\s/g, ''); // if it has empty parenthesis then is not valid if (/\(\)/.test(infix)) { return false; } // valid values: integers and identifiers var value = '(\\d+|[a-zA-Z_]\\w*)'; // the unary '+' and '-' var unaryOper = '[\\+\\-]?'; // the arithmetic operators var arithOper = '[\\+\\-\\*\\/]'; // the comparison operators var compOper = '(\\&lt;\\=?|\\&gt;\\=?|\\=\\=|\\!\\=)'; // if it has more than one comparison operator then is not valid if (infix.match(new RegExp(compOper, 'g')).length &gt; 1) { return false; } // the combined final regex: /[\+\-]?(\d+|[a-zA-Z_]\w*)(([\+\-\*\/]|(\&lt;\=?|\&gt;\=?|\=\=|\!\=))[\+\-]?(\d+|[a-zA-Z_]\w*))*/ var regex = new RegExp(unaryOper + value + '((' + arithOper + '|' + compOper + ')' + unaryOper + value + ')*'); // validate parenthesis balance for (var i = 0; i &lt; infix.length; i++) { if (infix[i] == '(') { balance++; } else if (infix[i] == ')') { balance--; } if (balance &lt; 0) { return false; } } if (balance &gt; 0) { return false; } // remove all the parenthesis infix = infix.replace(/[\(\)]/g, ''); return regex.test(infix); } </code></pre> <p>The idea is to check first the parenthesis balance, then remove them all given that we only want to validate and not evaluate, and then match the remaining expression to a regex (which may not be perfect, I'm not a regex expert). And... just in case: <code>infix</code> argument must be a string.</p> <h2>Edit</h2> <p>I noticed a couple of details and changed the code a bit:</p> <ol> <li>Added the operators you needed the regex to match too.</li> <li>Removed white spaces to get rid of regex junk.</li> <li>Checked if the expression had empty parenthesis.</li> <li>Checked if the expression had more than one comparison operators.</li> <li>Changed this <code>\+?\-?</code> by this <code>[\+\-]?</code>.</li> <li>Changed <a href="http://www.w3schools.com/jsref/jsref_match.asp" rel="nofollow">string <code>match</code> method</a> by <a href="http://www.w3schools.com/jsref/jsref_regexp_test.asp" rel="nofollow">regex <code>test</code> method</a> where possible.</li> <li>Changed this <code>[a-zA-Z0-9]</code> by this <code>(\d+|[a-zA-Z_]\w*)</code> since the first one matches wrong identifiers like <code>53abc</code>.</li> <li>For better understanding and clarity, extracted pieces of regex into separate variables and built the final one from these.</li> </ol> <p>Hope this is ok for you now :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload