jc127
jc127

Reputation: 352

Split an arithmetic expression with a regex

I want to split an expression like -1*-0.8/5-5 into [ '-1', '*', '-0.8', '/', '5', '-', '5' ]

[ '-1', '*', '-0.8', '/', '5-5' ] This is what I'm getting right now with expression.split(/([*/])/g);

Any suggestions on this?

Upvotes: 2

Views: 721

Answers (1)

Mistalis
Mistalis

Reputation: 18279

Here is a solution. It correctly detects +, -, /, * and accept the use of whitespaces:

([*\/]|\b\s*-|\b\s*\+)

var expression = "-1*-0.8/5-5";
console.log(expression.split(/([*\/]|\b\s*-|\b\s*\+)/g));

##Demo on regex101


From Wiktor's comment, here is an improvement accepting parenthesis

var expression = "-1 * -0.8 / (5 - 5)";
console.log(expression.split(/([*\/()]|\b\s*[-+])/g));

##Demo on regex101

Upvotes: 4

Related Questions