Reputation: 25
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
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+
In order to just match the negative numbers in your string, you'd need to make the -
required:
(?<!\d)-\d+
Upvotes: 1