用于分割数学表达式的正则表达式



我有一个表达式for "1+2-4*5+0.9+10.5+…"字符串格式,我想把它分成一个数组,这样表达式中从第二个开始的每个数字都与它之前的数学运算配对。(即"+ 2","4",">5,…])。我曾尝试使用regex/[-+*/][0-9]+|[-+*/][.0-9]+|[-+*/][0-9]+.[0-9]+/g,并成功地吐出整数,但小数点后的任何东西都没有被捕获(参见附件的代码片段)。我如何修改正则表达式的最后一部分(即[-+/][0-9]+.[0-9]+),使其适用于所有十进制分数?

expression="5-0.23+.65+.9+0.5+10.5";
const numArr=expression.match(/[-+*/][0-9]+|[-+*/][.0-9]+|[-+*/][0-9]+.[0-9]+/g);
console.log(numArr);
console.log("As you can see the regex is failing to capture decimals unless they start with a period(.)")

您可以在split()方法中使用正则表达式:

expression="5-0.23+.65+.9+0.5+10.5";
const numArr = expression.split(/(?=-)|(?=+)/g)
console.log(numArr)

最新更新