2

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?

Mistalis
  • 17,793
  • 13
  • 73
  • 97
jc127
  • 343
  • 2
  • 13
  • Perhaps, `/([*/]|\b-)/`. Your regex does not work with parentheses and `+` and the `/([*/]|\b-)/` won't work with them either. – Wiktor Stribiżew May 05 '17 at 09:42
  • *I want to split an expression* No, what you want to do is **parse** (or perhaps **lexically analyze**) an expression. For that, unsurprisingly, you should use a parser, or a lexical analyzer. Or, you could use any of a number of competent packages out there that parse/evaluate arithmetic expressions for a living. –  May 05 '17 at 10:07
  • Did [**my answer**](http://stackoverflow.com/a/43801821/4927984) solved your issue? – Mistalis May 11 '17 at 07:17
  • Yes, but I went with /(\b[*/+-])/ eventually, the spaces were pre-eliminated @Mistalis – jc127 May 11 '17 at 07:32

1 Answers1

4

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

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Mistalis
  • 17,793
  • 13
  • 73
  • 97
  • `.split(/([*/()]|\b\s*[-+])/).filter(Boolean))` is better. Also, you do not need the global modifier, `split` regex finds all matching strings and splits against them by default. – Wiktor Stribiżew May 05 '17 at 10:03