1

I've got the following String "$120 foo $100 bar" and I want to get just the last number so I end up with just "100".

I've had an attempt at it but can only get the first number (120) instead of the second number. This is what I have so far.

price.value.match(/\d+/);

Worth noting, on some occasions I may just have one number in the String "£80 GBP". I would like the regex to always give me the last number displayed.

Can anyone suggest the regex I should be using?

kboul
  • 13,836
  • 5
  • 42
  • 53
Daredevi1
  • 103
  • 3
  • 13
  • I suggest you experiment on a site such as regex101.com, after reading the documentation and boning up on things like the end-of-string anchor `$`. –  Jan 26 '17 at 13:39
  • `s.match(/\d+(?!.*\d)/)` should work if you have no line breaks in your strings. – Wiktor Stribiżew Jan 26 '17 at 13:40

2 Answers2

3

This one should suit your needs:

\d+(?=\D*$)

Regular expression visualization

Debuggex Demo

sp00m
  • 47,968
  • 31
  • 142
  • 252
1

You can get the last number like so:

(\d+)(?=[^\d]+$)

Demo:

https://regex101.com/r/K4cf5W/1

Mohammad Yusuf
  • 16,554
  • 10
  • 50
  • 78