Skip to content

Instantly share code, notes, and snippets.

@dedemenezes
Created July 1, 2025 18:00
Show Gist options
  • Save dedemenezes/4a74ec5b15bd6330457d420a487f9e46 to your computer and use it in GitHub Desktop.
Save dedemenezes/4a74ec5b15bd6330457d420a487f9e46 to your computer and use it in GitHub Desktop.
def parse_url(url)
# p url
regex = /^(?<scheme>https?):\/{2}(?<subdomain>w{3})\.(?<domain>\w+)(?<top_level_domain>\.\w+)\/?(?<path>[\w\/]+)\??(?<query_params>[&=\w]*)/
match_data = url.match(regex)
# p match_data
#<MatchData "http://www.lewagon.com" scheme:"http" subdomain:"www" domain:"lewagon" top_level_domain:".com">
query_params = match_data[:query_params].scan(/(\w+)=(\w+)/)
# p query_params #=> [["search", "currywurst"]]
params = {}
query_params.each do |param|
# ["search", "currywurst"]
params[param[0].to_sym] = param[1]
end
# p params
{
scheme: match_data[:scheme],
subdomain: match_data[:subdomain],
domain: match_data[:domain],
top_level_domain: match_data[:top_level_domain],
path: match_data[:path].split('/'),
params: params
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment