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
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 )
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.