Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing repeated matches from a ruby string?

Maybe I'm just pretty tired, but I don't see an obvious way to parse out the numbers from a string like this:

some text here, and then 725.010, 725.045, 725.340 and 725.370; and more text

One thing that occurred to me: split this by spaces into an array. Then apply a regex test with a group to each element in the array.

Is there a cleaner, simpler way to do this?

like image 251
Dogweather Avatar asked Dec 28 '22 04:12

Dogweather


2 Answers

You need String#scan:

your_string.scan(/\d\d\d\.\d\d\d/)

will output array of matches.

like image 117
Nakilon Avatar answered Jan 12 '23 15:01

Nakilon


result = subject.scan(/\d+(?:\.\d+)?/)

This will find integers or decimals in a string and put them (still as strings, though) into the array result.

like image 26
Tim Pietzcker Avatar answered Jan 12 '23 16:01

Tim Pietzcker