trrrrrrm
trrrrrrm

Reputation: 11802

javascript Regular Expressions Issue

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

}

Upvotes: 2

Views: 182

Answers (2)

YOU
YOU

Reputation: 123791

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;
}

Upvotes: 1

ardsrk
ardsrk

Reputation: 2447

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.

Upvotes: 0

Related Questions