rubyist
rubyist

Reputation: 3132

Regular expression in ruby?

I have a URL like below.

/shows/the-ruby-book/meta-programming/?play=5b35a825-d372-4375-b2f0-f641a38067db"

I need to extract only the id of the play (i.e. 5b35a825-d372-4375-b2f0-f641a38067db) using regular expression. How can I do it?

Upvotes: 0

Views: 93

Answers (4)

spickermann
spickermann

Reputation: 107107

I would not use a regexp to parse a url. I would use Ruby's libraries to handle URLs:

require 'uri'

url = '/shows/the-ruby-book/meta-programming/?play=5b35a825-d372-4375-b2f0-f641a38067db'

uri = URI.parse(url)
params = URI::decode_www_form(uri.query).to_h

params['play']
# => 5b35a825-d372-4375-b2f0-f641a38067db

Upvotes: 4

the Tin Man
the Tin Man

Reputation: 160621

Ruby's built-in URI class has everything needed to correctly parse, split and decode URLs:

require 'uri'

uri = URI.parse('/shows/the-ruby-book/meta-programming/?play=5b35a825-d372-4375-b2f0-f641a38067db')
URI::decode_www_form(uri.query).to_h['play'] # => "5b35a825-d372-4375-b2f0-f641a38067db"

If you're using an older Ruby that doesn't support to_h, use:

Hash[URI::decode_www_form(uri.query)]['play'] # => "5b35a825-d372-4375-b2f0-f641a38067db"

You should use URI, rather than try to split/extract using a regexp, because the query of a URI will be encoded if any values are not within the characters allowed by the spec. URI, or Addressable::URI, will decode those back to their original values for you.

Upvotes: 0

Bala
Bala

Reputation: 11274

url = '/shows/the-ruby-book/meta-programming/?play=5b35a825-d372-4375-b2f0-f641a38067db'
url.split("play=")[1] #=> "5b35a825-d372-4375-b2f0-f641a38067db"

Upvotes: 1

arco444
arco444

Reputation: 22871

You can do:

str = '/shows/the-ruby-book/meta-programming/?play=5b35a825-d372-4375-b2f0-f641a38067db'
match = str.match(/.*\?play=([^&]+)/)
puts match[1]

=> "5b35a825-d372-4375-b2f0-f641a38067db"

The regex /.*\?play=([^&]+)/ will match everything up until ?play=, and then capture anything that is not a & (the query string parameter separator)

A match will create a MatchData object, represented here by match variable, and captures will be indices of the object, hence your matched data is available at match[1].

Upvotes: 1

Related Questions