1

I have a string that looks like this:

Results 1 - 10 of 20

How would I find the number 10 and 20 of that sentence using regex in Ruby?

Something like:

first_number, second_number = compute_regex(my_string)...

Thanks

2 Answers 2

1

Like so:

first, second = *source.scan(/\d+/)[-2,2]

Explanation

\d+ matches any number

scan finds all matches of its regular expression argument in source

[-2,2] returns the last two numbers in an array: starts at index -2 from end, returns next 2

* splat operator unpacks these two matches into the variables first and second (NOTE: this operator is not necessary, you can remove this, and I like the concept)

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

1 Comment

The splat isn't strictly necessary is it?
0

Try this:

a = "Results 1 - 10 of 20"
first_number, second_number = a.match(/\w+ (\d) \- (\d+) of (\d+)/)[2..3].map(&:to_i)

The map piece is necessary because the regexp MatchData objects returned are strings.

Comments

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.