首页 > 解决方案 > 用于拆分数学表达式的正则表达式

问题描述

我有一个字符串格式的 for "1+2-4*5+0.9+10.5+..." 表达式,我想将它拆分为一个数组,以便表达式中从第二个开始的每个数字都与之前的数学运算。(即[“+2”,“-4”,“ 5,...])。我尝试使用正则表达式/[-+*/][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(.)")

标签: javascript

解决方案


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

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


推荐阅读