Reputation: 1
I'm running the following to catch a series of numerical values (floats and integers) in a string:
Example:
x = "This is the 1st string with 2 quotes and took 3.4 seconds to write."
Running
x.scan(/\d+(\.\d+)?/)
returns
[[nil], [nil], [".4"]]
but I'm looking for
[["1"], ["2"], ["3.4"]]
What am I doing wrong here? Or is there a better way to approach this?
Upvotes: 0
Views: 216
Reputation: 70297
From the Ruby docs:
If the pattern contains no groups, each individual result consists of the matched string,
$&
. If the pattern contains groups, each individual result is itself an array containing one entry per group.
Since your pattern contains a capture group, you're getting the latter behavior. Making the group non-capturing gives you what you want.
x.scan(/\d+(?:\.\d+)?/)
Upvotes: 1