[英]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 我希望RE匹配可以添加到该数字的任何数学方程式
EXAMPLE
+10+20+30 //accepted
**10 //rejected
-10- // rejected
10 // rejected
%10 //accepted
*(10+10)-10 //accepted
please help me 请帮我
} }
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;
}
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. 为算术表达式编写上下文无关的语法 ,并使用解析器生成器(如Jison)从您的给定语法在javascript中生成解析器。
An example CFG for mathemical expressions 用于数学表达式的CFG示例
On the Jison page scroll down to the section "Specifying a language" . 在“ Jison”页面上,向下滚动到“指定语言”部分 。 That section gives a language grammar to parse arithmetic expressions.
该部分提供了一种语法分析语法表达式。 Hope this helps.
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.