Reputation: 9734
I need to extract hostname and port (if any) from an URL and here below is my code:
val regEx = """^(?:https?:\/\/)?(?:www\.)?(.*?)\//""".r
val url = regEx.split("http://www.domain.com:8080/one/two")
val hostname = url(url.length - 1).split("/")(0).split(":")(0)
val hasPort = url(url.length - 1).split("/")(0).split(":").length > 1
val port = if (hasPort) url(url.length - 1).split("/")(0).split(":")(1) else 80
The code above works as expected... but for sure in Scala there is a better way to get the same result.
How do I get hostname and port (if any) without using all those ugly split
s?
Upvotes: 6
Views: 7197
Reputation: 108121
Without reinventing the wheel, you can simply leverage java.net.URL
val url = new java.net.URL("http://www.domain.com:8080/one/two")
val hostname = url.getHost // www.domain.com
val port = url.getPort // 8080
A minor difference, getPort
returns -1
if no port is specified, so you have to handle that case explicitly.
val port = if (url.getPort == -1) url.getDefaultPort else url.getPort
Upvotes: 19