Capturing groups not working as expected with Ruby scan method
I need to get an array of floats (both positive and negative) from a multi-line string. For example: -45.124, 1124.325
etc.
That's what I'm doing:
text.scan(/(\+|\-)?\d+(\.\d+)?/)
While it works fine on regex101 (capturing group 0 matches everything I need), it doesn't work in Ruby code.
Any ideas why this is happening and how I can improve it?
source to share
You have to remove the capturing groups or make them non-capturing:
text = " -45.124, 1124.325"
puts text.scan(/[+-]?\d+(?:\.\d+)?/)
See demo , output:
-45.124
1124.325
See scan
documentation :
If the template contains no groups, each individual result consists of a matched string
$&
. If the template contains groups, each individual result is itself an array containing one entry for each group.
Well, if you need to match floats as well, such as .04
, you can use [+-]?\d*\.?\d+
. See another demo
source to share