4

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?

1
  • Thanks for the answers, everyone. I had forgotten about String#scan. These are statute numbers, by the way. Commented Dec 11, 2010 at 16:03

2 Answers 2

5

You need String#scan:

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

will output array of matches.

Sign up to request clarification or add additional context in comments.

Comments

5
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.

1 Comment

To get them as floats, just do result = subject.scan(/\d+(?:\.\d+)?/).map(&:to_f).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.