Java - Write code to get Host name from a string using regex

Requirements

Write code to get Host name from a string using regex

Demo

//package com.book2s;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] argv) {
        String url = "www.book2s.com";
        System.out.println(getHost(url));
    }//ww w. j  a va  2  s  .  c o  m

    public static String getHost(String url) {
        if (url == null || "".equals(url.trim()))
            return null;

        Pattern p = Pattern.compile("(?<=//|)((\\w)+\\.)+\\w+");
        Matcher matcher = p.matcher(url);
        if (matcher.find())
            return matcher.group();
        else
            return null;
    }
}

Related Exercise