What is the most elegant way to get a domain extension?

for example

google.com -> .com

google.co.id -> .co.id

hello.google.co.id -> .co.id

in vb.net?

Can this be done?

+4
source share
1 answer

Assuming areas with different "." must include ".co". bit, you can use this code:

Dim input As String = "hello.google.co.id"
Dim extension As String = ""
If (input.ToLower.Contains(".co.")) Then
    extension = input.Substring(input.ToLower.IndexOf(".co."), input.Length - input.ToLower.IndexOf(".co."))
Else
    extension = System.IO.Path.GetExtension(input)
End If

UPDATE

As suggested in the comments, the above code does not account for quite a lot of events (e.g. .ca.us). The version below stems from another assumption (.xx.yy can only be present if there are groups of 2 characters), which should take care of all possible alternatives:

If (input.ToLower.Length > 4 AndAlso input.ToLower.Substring(0, 4) = "www.") Then input = input.Substring(4, input.Length - 4) 'Removing the starting www.  

Dim temp() As String = input.Split(".")

If (temp.Count > 2) Then
    If (temp(temp.Count - 1).Length = 2 AndAlso temp(temp.Count - 2).Length = 2) Then
        'co.co or ca.ca, etc.
        extension = input.Substring(input.ToLower.LastIndexOf(".") - 3, input.Length - (input.ToLower.LastIndexOf(".") - 3))
    Else
        extension = System.IO.Path.GetExtension(input)
    End If
Else
    extension = System.IO.Path.GetExtension(input)
End If

, , ( , ) 100% . , , , ; : "hello.ue.co". , (, , , ), , .

+3

All Articles