Shankar
Shankar

Reputation: 69

Extract complete url from a text in android

I want to extract complete url from a large text such that the complete url incuding the parameters are needed to be extraxted.

It should support all url format...

Eg of urls

  1. www.facebook.com/mainhoon/jikii/50
  2. http://www.alphabet.com?user=50&tyn=40
  3. m.gmail.com etc

Eg of text:

hi hello howe are you look at my code http://www.stackoverflow.com?adiadajda here we got the answer also check this url www.myspace.in that gives bla bla bla

Upvotes: 3

Views: 4258

Answers (2)

Extract single url via Kotlin

private fun extractUrl(input: String) =
        input
            .split(" ")
            .firstOrNull { Patterns.WEB_URL.matcher(it).find() }

Upvotes: 8

Prasanna Anbazhagan
Prasanna Anbazhagan

Reputation: 1725

You try to parse the whole Strings from the text and then compare each string to match for url. If that string has url pattern then that string is a complete url.

Eg. hi this is my fb profile www.facebook.com/prasilabs check it.

in that example if we get all the string and check for url pattern we will get the url www.facebook.com/prasilabs

public static List<String> extractUrls(String input)
{
    List<String> result = new ArrayList<String>();

    String[] words = input.split("\\s+");


    Pattern pattern = Patterns.WEB_URL;
    for(String word : words)
    {
        if(pattern.matcher(word).find())
        {
            if(!word.toLowerCase().contains("http://") && !word.toLowerCase().contains("https://"))
            {
                word = "http://" + word;
            }
            result.add(word);
        }
    }

    return result;
}

Upvotes: 4

Related Questions