Although there are many regex questions related to my issue, none of them address my specific problem as I do not have parentheses in my expressions.
Let's take a look at an example: 1*2+3-99/50
I am trying to tokenize this expression in order to convert it to post-fix notation. My first attempt was to use split with regex like this:
'1*2+3-99/50'.split(/([+\-*/])/) // operands have no unary (-)
// ['1', '*', '2', '+', '3', '-', '99', '/', '50']
It seems to work perfectly for binary operators but when dealing with unary operators, it falls short. I then attempted to utilize a lookahead to detect if a minus sign comes after another operator:
'1*-2+-3--99/-50'.split(/([+\-*/])(?=-)/ // all operands have unary (-)
// ['1', '*', '-2', '+', '-3', '-', '-99', '/', '-50']
This method also works, but the caveat is that all numbers already have negative signs attached to them.
I've tried capturing operands with unary (-) operators separately and appending them to the final tokens, but it messes up the order which is crucial for evaluation. I also looked into conditional regex but it doesn't seem applicable in my scenario.
Is it feasible to split tokens containing negative signs in one single split action?