get Host from URL String - Java java.util.regex

Java examples for java.util.regex:Match URL

Description

get Host from URL String

Demo Code

//package com.java2s;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] argv) {
        String url = "http://java2s.com";
        System.out.println(getHost(url));
    }/*from www  .  ja  v a2  s .c  o m*/

    public static String getHost(final String url) {
        if (url == null || url.trim().equals("")) {
            return "";
        }
        String host = "";
        Pattern p = Pattern.compile("(?<=//|)((\\w)+\\.)+\\w+");
        Matcher matcher = p.matcher(url);
        if (matcher.find()) {
            host = matcher.group();
        }
        return host;
    }
}

Related Tutorials