Regex for a splitting a mathematical expression

I have an expression of for "1+2-4*5+0.9+10.5+…" in string format and I want to split it into an array so that every number from the second one onwards in the expression is paired with the math operation before it. (i.e. ["+2","-4","5,…]). I have attempted using regex /[-+*/][0-9]+|[-+*/][.0-9]+|[-+*/][0-9]+\.[0-9]+/g and am succeeding in spitting whole numbers but anything after a decimal point is not captured (see attached code snippet). How do I modify the last part of the regex (i.e. [-+/][0-9]+.[0-9]+) so that it works properly for all decimal fraction?

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

39 thoughts on “Regex for a splitting a mathematical expression”

  1. 785822 550423Hmm is anyone else having problems with the images on this blog loading? Im trying to figure out if its a difficulty on my end or if its the weblog. Any responses would be greatly appreciated. 237390


Leave a Comment