views:

76

answers:

2

i have posted a previous question about Regular Expressions and this is another question it's not duplicate ... sorry for that

Hello I really need some help in Regular Expressions, i'm working on a function like

var x = 0;

function doMath(myVar){

RE = //; // here is the problem 
if(RE.test(myVar))
  eval(x+myVar)
else
return false;

}

i want the RE to match any math equation that could be added to that number like

EXAMPLE 
+10+20+30 //accepted
**10 //rejected
-10- // rejected
10 // rejected
%10 //accepted
*(10+10)-10 //accepted

please help me

}

+1  A: 

How about just do the test for valid characters (to prevent some code injections), and then try "eval"-ing it?

function doMath(myVar){
    if (/^[0-9()%*\/+-]+$/.test(myVar)){
        try{
             return eval(myVar);
        }catch(e){}
    }
    return false;
}
S.Mark
I was just writing the same 4 hours ago when by boss came in :P. You should note the validation also prevents code injection (for example, if the text comes from the query string).
Kobi
Thanks @Kobi, added few words, but I am not 100% sure, its prevent code injection completely. :-) I havn't see any injections that use only 0-9 and math operators though.
S.Mark
A: 

As mentioned in the comments arithmetic equations are not regular so don't handle them using regular expressions.

Write a Context-free grammar for arithmetic expressions and use a parser generator like Jison that generates a parser in javascript from your given grammar.

An example CFG for mathemical expressions

On the Jison page scroll down to the section "Specifying a language". That section gives a language grammar to parse arithmetic expressions. Hope this helps.

ardsrk