Alex
Alex

Reputation: 431

Regex match last whole number

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

Answers (3)

Avinash Raj
Avinash Raj

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

Ares Draguna
Ares Draguna

Reputation: 1661

Try this:

(\d+)(?!.*\d)

Or this:

.*(?:\D|^)(\d+)

Hope it helps!
Keep on coding,
Ares.

Upvotes: 0

elixenide
elixenide

Reputation: 44823

Best option:

You need a look-ahead assertion, like this:

(\d+)(?=\D*$)

Demo

Alternative option:

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

Related Questions