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?
"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(...)
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
.