Extract last numbers with Regex

Asked

Viewed 752 times

0

I have these two examples of strings:

/news/uk-news/commuter-who-extraordinary-row-woman-12345
/news/weird/dude-who-killed-14-extraordinary-98765.amp

I just want to get the latest numbers, 12345 and 98765, respectively.

In the middle of the string, there may be other numbers. And at the end, there may be other characters (or not) that are not numbers. What I’d really like is the latest numbers, after the last hyphen -.

I tried with (\w+-)(\d+)(\W*), but returned only a part. Can someone please help me with a correct solution?

  • solved! Thank you very much!

  • this business of lookaround is potent!

  • rs.. truth. Facilitates a lot.

1 answer

1


This regex will only take the last numeric sequence (or only the last number) of the string:

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

Examples:

/news/uk-news/commuter-who-extraordinary-row-woman-12345
// retorna 12345

/news/weird/dude-who-killed-14-extraordinary-98765.amp
// retorna 98765

/qualquer15coisa-20.-s10.amp
// retorna 10

foo.1.10.foo
// retorna 10

Browser other questions tagged

You are not signed in. Login or sign up in order to post.