How to parse a URL and extract the required substr

2019-01-15 01:38发布

Say I have a string like this: "http://something.example.com/directory/"

What I want to do is to parse this string, and extract the "something" from the string.

The first step, is to obviously check to make sure that the string contains "http://" - otherwise, it should ignore the string.

But, how do I then just extract the "something" in that string? Assume that all the strings that this will be evaluating will have a similar structure (i.e. I am trying to extract the subdomain of the URL - if the string being examined is indeed a valid URL - where valid is starts with "http://").

Thanks.

P.S. I know how to check the first part, i.e. I can just simply split the string at the "http://" but that doesn't solve the full problem because that will produce "http://something.example.com/directory/". All I want is the "something", nothing else.

标签: ruby parsing
3条回答
Juvenile、少年°
2楼-- · 2019-01-15 01:42

Well, you can use regular expressions. Something like /http:\/\/([^\.]+)/, that is, the first group of non '.' letters after http. Check out http://rubular.com/, you can test your regular expressions against a set of tests too, it's great for learning this tool :)

查看更多
男人必须洒脱
3楼-- · 2019-01-15 01:59

You could use URI like

uri = URI.parse("http://something.example.com/directory/")
puts uri.host
# "something.example.com"

and you could then just work on the host.
Or there is a gem domainatrix from Remove subdomain from string in ruby

require 'rubygems'
require 'domainatrix'

url = Domainatrix.parse("http://foo.bar.pauldix.co.uk/asdf.html?q=arg")
url.public_suffix       # => "co.uk"
url.domain              # => "pauldix"
url.subdomain           # => "foo.bar"
url.path                # => "/asdf.html?q=arg"
url.canonical           # => "uk.co.pauldix.bar.foo/asdf.html?q=arg"

and you could just take the subdomain.

查看更多
Lonely孤独者°
4楼-- · 2019-01-15 02:01

I'd do it this way:

require 'uri'

uri = URI.parse('http://something.example.com/directory/')
uri.host.split('.').first
=> "something"

URI is built into Ruby. It's not the most full-featured but it's plenty capable of doing this task for most URLs. If you have IRIs then look at Addressable::URI.

查看更多
登录 后发表回答