Detect and extract url from a string?

We can get URL from the text or String.

/** * Returns a list with all links contained in the input */ public static List<String> extractUrls(String text) { List<String> containedUrls = new ArrayList<String>(); String urlRegex = "((https?|ftp|gopher|telnet|file):((//)|(\\\\))+[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&]*)"; Pattern pattern = Pattern.compile(urlRegex, Pattern.CASE_INSENSITIVE); Matcher urlMatcher = pattern.matcher(text); while (urlMatcher.find()) { containedUrls.add(text.substring(urlMatcher.start(0), urlMatcher.end(0))); } return containedUrls; }




Example:

List<String> extractedUrls = extractUrls("Welcome to https://stackoverflow.com/ and here is another link http://www.google.com/ \n which is a great search engine");

for (String url : extractedUrls)
{
    System.out.println(url);
}

Prints:
https://stackoverflow.com/
http://www.google.com/

link: https://stackoverflow.com/questions/5713558/detect-and-extract-url-from-a-string

Comments

Popular posts from this blog

Can't import database through phpmyadmin file size too large xampp

incompatible hax module version 3 requires minimum version 4 no accelerator found

how to use text box in android studio