Seal
Seal

Reputation: 1060

How to extract number out of url string ruby

how would I extract the last part of the string with a regex? The last part of the string will always be a 3 digit number as well.

"/gdc/md/vin06hdpq8442qocut9aoih8q5j5k43u/obj/185"

Upvotes: 0

Views: 1148

Answers (4)

Drenmi
Drenmi

Reputation: 8777

There are a number of different ways you can accomplish this.

You can use regular expressions to match either all trailing digits (/\d+$/), or just the last three trailing digits (/\d{3}$/), depending on what behaviour you want in case the string for some reason has more digits than you expected:

str.match(/\d+$/)[0]
#=> "185"

str.match(/\d{3}$/)[0]
#=> "185"

Another option is to split the string into an array, using / as the separator, and then grabbing the last element (which will contain everything past the last /.)

str.split("/").last
#=> "185"

Or you can use the fact that substrings can be accessed using indices, much like arrays, and use it to grab the last three digits:

str[-3, 3]
#=> "185"

Unless you're doing this thousands of times inside a loop, any performance difference will be insignificant, so you can go for the option that is offer the most robustness and legibility.

Note that in all four cases, you will be returned a string, so if you intend to use this number as an integer, you'll need to first convert it using #to_i.

Upvotes: 1

Bassel Samman
Bassel Samman

Reputation: 802

Or a combination of both with str[/\d{3}$/]

or maybe str[-3..-1]

So many ways to skin that string :)

Upvotes: 0

steenslag
steenslag

Reputation: 80065

Just slice the last 3 chars :

str = "/gdc/md/vin06hdpq8442qocut9aoih8q5j5k43u/obj/185"
p str[-3,3] # => "185"

Upvotes: 2

philip yoo
philip yoo

Reputation: 2522

Something like: /\d+$/ should get all digits at the end of the string

Upvotes: 2

Related Questions