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?
/[-+*/][0-9]+|[-+*/][.0-9]+|[-+*/][0-9]+.[0-9]+/g
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(.)")
You can use a regex inside a split() method:
expression="5-0.23+.65+.9+0.5+10.5"; const numArr = expression.split(/(?=-)|(?=+)/g) console.log(numArr)
1.4m articles
1.4m replys
5 comments
57.0k users