本文介绍了在运算符上拆分数学表达式,并将运算符包括在输出数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在数学运算符上拆分数学字符串.例如

I'm trying to split the mathematical strings on maths operators. for example

表达式="7 * 6 + 3/2-5 * 6 +(7-2)* 5"

我需要将其标记化以产生:

I need to tokenize it to produce:

expressionArray = ["7","*","6","+","3","/","2",-","5","*","6]

我试图在这里找到解决方案,这就是我得到的

I tried finding the solution here and this is what i get

expressoinArray=expression.split("(?<=[-+*/])|(?=[-+*/]")

,但看起来这无法为 expression 提取所需的结果.

but looks like this is not fetching the desired result for expression.

推荐答案

jsfiddle

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

这篇关于在运算符上拆分数学表达式,并将运算符包括在输出数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 02:26