Search code examples
c#regexshunting-yard

Get negative numbers from expression


I'm trying to separate the tokens on a string expression. The expression looks like this:

-1-2+-3

This is the regex I'm using:

[\d\.]+|[-][\d\.]+|\+|\-|\*|\/|\^|\(|\)

This brings me these matches:

-1
-2
+
-3

I was expecting:

-1
-
2
+
-3

Any ideas how can I distinct negative numbers from operators?


Solution

  • Maybe you could try this one; it makes use of a look-behind:

    ((?<=\d)[+*\/^()-]|\-?[\d.]+)
    

    I tested it here.

    Basically, makes sure that there is a number before the operator to decide what to match. So, if there is a digit before the operator, treat the operator alone, otherwise, combine the minus with the digit.

    EDIT: Separated the brackets from the lot, just in case (demo):

    ((?<=\d)[+*\/^-]|[()]|\-?[\d.]+)