Home > database >  Regex capture negative numbers in sum
Regex capture negative numbers in sum

Time:11-14

Is there a way using regex to capture negative numbers in an equation. So given string "6 -9" -9 would be the negative number.

Logically speaking, the regex would need to:

  • look for any numbers (n-1) with a "-" preceding it

  • check the item preceding that (n-2) ins't a number, because 2-2 is still a valid equation. So "6 -9-2" would only return one negative number of -9.

    or

    appears at the begining of the string. So "-6 -9-2" would return 2 negative number of -6 and-9.

CodePudding user response:

Based on your rules it boils down to "no numbers preceding a negative number".

Assuming no whitespace between numbers ...

These answers use a simple negative lookbehind for any digit before a - character at the beginning of a negative number.

For Decimal

(?<!\d\.?)-(\d (\.\d*)?|\.\d )

Supports numbers like:

  • -1234.5678
  • -.5678
  • -1234.

For Integer

(?<!\d)-\d 

Supports numbers like:

  • -1234
  • Related