Reputation: 431
I need to extract the last number from strings like
10-20 days // should extract 20
from 10 to 30 days // should extract 30
between 5 and 12 days //should extract 12
Iv tried with this pattern ^.+([0-9]+)[^\d]days.$ but it takes only the last digit not the whole number.
Upvotes: 0
Views: 2796
Reputation: 174696
You could use a Positive lookahead assertion.
\d+(?=\D*$)
Explanation:
\d+ digits (0-9) (1 or more times)
(?= look ahead to see if there is:
\D* non-digits (all but 0-9) (0 or more
times)
$ before an optional \n, and the end of
the string
) end of look-ahead
Upvotes: 3
Reputation: 1661
Try this:
(\d+)(?!.*\d)
Or this:
.*(?:\D|^)(\d+)
Hope it helps!
Keep on coding,
Ares.
Upvotes: 0
Reputation: 44823
You need a look-ahead assertion, like this:
(\d+)(?=\D*$)
Or you can modify your current pattern with a ?
:
^.+?([0-9]+)[^\d]days.?$
The first ?
makes the .+
non-greedy. Also note the ending ?
- you don't have any characters after days
in your examples. Demo
Upvotes: 2