我正在尝试拆分数学运算符的数学字符串。例如
expression = "7*6+3/2-5*6+(7-2)*5"
我需要对其进行标记以产生:
expressionArray = ["7","*","6","+","3","/","2","-","5","*","6"]
我试着在这里找到解决方案,这就是我得到的
expressoinArray=expression.split("(?<=[-+*/])|(?=[-+*/]")
但看起来这并没有为expression
.
我正在尝试拆分数学运算符的数学字符串。例如
expression = "7*6+3/2-5*6+(7-2)*5"
我需要对其进行标记以产生:
expressionArray = ["7","*","6","+","3","/","2","-","5","*","6"]
我试着在这里找到解决方案,这就是我得到的
expressoinArray=expression.split("(?<=[-+*/])|(?=[-+*/]")
但看起来这并没有为expression
.
var expression = "7.2*6+3/2-5*6+(7-2)*5";
var copy = expression;
expression = expression.replace(/[0-9]+/g, "#").replace(/[\(|\|\.)]/g, "");
var numbers = copy.split(/[^0-9\.]+/);
var operators = expression.split("#").filter(function(n){return n});
var result = [];
for(i = 0; i < numbers.length; i++){
result.push(numbers[i]);
if (i < operators.length) result.push(operators[i]);
}
console.log(result);
编辑:
这就像接受的答案一样,并且由于filter()
在 IE8 及以下版本中不会失败:
var expression = "7.2*6+3/2-5*6+(7-2)*5";
var splitUp = expression.match(/[^\d()]+|[\d.]+/g);
document.body.innerHTML = splitUp;
首先,如果你想使用正则表达式,split()
你必须先创建它:
var expr = new RegExp("(?<=[-+*/])|(?=[-+*/])")
// note: you missed a ) at the end
可悲的是,大多数浏览器中的 RegExp 引擎不支持后视,所以无论如何它都不会工作。您必须循环执行此操作。