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

时间:2021-01-28 16:44:48

标签: javascript

我有一个字符串格式的 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(.)")

1 个答案:

答案 0 :(得分:1)

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

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