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?

+3


source to share


2 answers


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

+5


source


([+-]?\d+\.\d+)

      

assumes there is a leading digit before the decimal point



see demo in Rubular

+1


source







All Articles