Reputation: 4617
I'm trying to pull the user_id from a foursquare URL, like this one:
https://foursquare.com/user/99999999
The following regex pulls exactly what I need (a series of numbers that terminate with the end of the line):
\d+$
However, I'm not sure how to set a string equal to the matched characters. I'm aware of sub and gsub, but those methods substitute a matched string for something else.
I'm looking for a way to specifically pull the section of a string that matches my regex (if it exists)
Upvotes: 4
Views: 10565
Reputation: 18784
I like to use the return of match():
Anything wrapped in a capture () in the regex, gets assigned to the match result array
"https://foursquare.com/user/99999999".match(/(\d+)\z/)[1] #=> "99999999"
Upvotes: 11
Reputation: 16241
>> "https://foursquare.com/user/99999999"[/(\d+)\z/, 1]
=> "99999999"
>> "https://foursquare.com/user/99999999" =~ /(\d+)\z/
=> 28
>> $1
=> "99999999"
>> "https://foursquare.com/user/99999999".split('/').last
=> "99999999"
There are many ways. I personally like String#[]
though
Upvotes: 5