Skip to content Skip to sidebar Skip to footer

What's The Best Way To Check If A String Contains A Url In Java/android?

What's the best way to check if a String contains a URL in Java/Android? Would the best way be to check if the string contains |.com | .net | .org | .info | .everythingelse|? Or is

Solution 1:

Best way would be to use regular expression, something like below:

publicstaticfinalStringURL_REGEX="^((https?|ftp)://|(www|ftp)\\.)?[a-z0-9-]+(\\.[a-z0-9-]+)+([/?].*)?$";

Patternp= Pattern.compile(URL_REGEX);
Matcherm= p.matcher("example.com");//replace with string to compareif(m.find()) {
    System.out.println("String contains URL");
}

Solution 2:

This is simply done with a try catch around the constructor (this is necessary either way).

StringinputUrl= getInput();
if (!inputUrl.contains("http://"))
    inputUrl = "http://" + inputUrl;

URL url;
try {
    url = newURL(inputUrl);
} catch (MalformedURLException e) {
    Log.v("myApp", "bad url entered");
}
if (url == null)
    userEnteredBadUrl();
elsecontinue();

Solution 3:

After looking around I tried to improve Zaid's answer by removing the try-catch block. Also, this solution recognizes more patterns as it uses a regex.

So, firstly get this pattern:

// Pattern for recognizing a URL, based off RFC 3986privatestaticfinalPattern urlPattern =Pattern.compile(
    "(?:^|[\\W])((ht|f)tp(s?):\\/\\/|www\\.)"+"(([\\w\\-]+\\.){1,}?([\\w\\-.~]+\\/?)*"+"[\\p{Alnum}.,%_=?&#\\-+()\\[\\]\\*$~@!:/{};']*)",
    Pattern.CASE_INSENSITIVE|Pattern.MULTILINE|Pattern.DOTALL);

Then, use this method (supposing str is your string):

// separate input by spaces ( URLs don't have spaces )String [] parts = str.split("\\s+");

    // get every partfor( String item : parts ) {
        if(urlPattern.matcher(item).matches()) { 
            //it's a good url
            System.out.print("<a href=\"" + item + "\">"+ item + "</a> " );                
        } else {
           // it isn't a url
            System.out.print(item + " ");    
        }
    }

Solution 4:

Based on Enkk's answer, i present my solution:

publicstaticbooleancontainsLink(String input) {
    boolean result = false;

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

    for (String item : parts) {
        if (android.util.Patterns.WEB_URL.matcher(item).matches()) {
            result = true;
            break;
        }
    }

    return result;
}

Solution 5:

Old question, but found this, so I thought it might be useful to share. Should help for Android...

Post a Comment for "What's The Best Way To Check If A String Contains A Url In Java/android?"