extract URL from String - Java java.util.regex

Java examples for java.util.regex:Match URL

Description

extract URL from String

Demo Code


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

public class Main {
    public static void main(String[] argv) {
        String text = "java2s.com this is a test http://java2s.com test test";
        System.out.println(java.util.Arrays.toString(extractURL(text)));
    }/*  ww  w  . j  a  v  a 2  s .c o m*/

    public static String[] extractURL(String text) {
        List<String> list = new ArrayList<String>();
        Pattern pattern = Pattern
                .compile(
                        "(http://|https://){1}[\\w\\.\\-/:\\#\\?\\=\\&\\;\\%\\~\\+]+",
                        Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(text);
        while (matcher.find()) {
            list.add(matcher.group());
        }
        return list.toArray(new String[list.size()]);
    }
}

Related Tutorials