NullOne
NullOne

Reputation: 25

c# regex get only negative numbers in string

So my task is to choose only negative numbers in my string. However, there is a big problem. My string constists of different minuses (some for negative numbers, some for subtracting).

My idea is to get negative numbers, if there are no more digits before the minus. My regex pattern:

(\d{0}-)?\d+

The same pattern that doesn't work as I thought:

((?!\d)-)?\d+

And I test this pattern on this text:

-1 2 (33-44)

My expection: -1 2 33 44

Result: -1 2 33 -44

As you can see the last minus is used for subtracting, it doesn't mean a negative number.

Upvotes: 2

Views: 980

Answers (1)

Tobias Tengler
Tobias Tengler

Reputation: 7454

You could get your expected result by using Negative Lookbehind (?<!), checking if there are one or more numbers ahead of the -:

(?<!\d+)-?\d+

Example

In order to just match the negative numbers in your string, you'd need to make the - required:

(?<!\d)-\d+

Example

Upvotes: 1

Related Questions