0

I need to extract a float from a string in Ruby, but if I try to extract it with the normal \d I of course don't fetch the digits in front of the ",".

"3,25 år -".match((\d+)\s?år\s?-)[1] => # "25"

Is there an easy way to fetch the whole number?

Severin
  • 7,778
  • 10
  • 62
  • 106

2 Answers2

2
"3,25 år -".match(/([\d,]+)\s?år\s?-/)[1] => # "3,25"

Pay attention that your code also had another error. You were missing the regex delimiters. It should be

match(/.../)

not

match(...)
Simone Carletti
  • 164,184
  • 42
  • 341
  • 356
  • 1
    Thanks @psxls. Also thanks for pointing me to the Scuba Diving proposal. I'm a Scuba Instructor, I've added the proposal to my profile, it may help to advertise it a little bit. – Simone Carletti Dec 01 '13 at 16:21
0

You are missing the forward slashes / around the regular expression.

Apart of that, this will return what you want:

"3,25 år -".match(/(\d+(?:,\d+)?)\s?år\s?-/)[1] => # "3,25"

As a side note, the above will match both positive integers and floats. If you are sure you will always have floats, simplify it like that:

"3,25 år -".match(/(\d+,\d+)\s?år\s?-/)[1] => # "3,25"

Finally, I would propose you to get used to the [0-9] notation for digits instead of \d, ready why here, so finally try this:

"3,25 år -".match(/([0-9]+,[0-9]+)\s?år\s?-/)[1] => # "3,25"

PS. I would suggest you to avoid the [\d,]+ solutions since this regular expression can match also non-numbers, eg it will match 1,,1 or 1, or ,1.

Community
  • 1
  • 1
psxls
  • 6,577
  • 6
  • 27
  • 49