Skip to content
Advertisement

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 there a better way to do it?

The url is entered into a EditText in Android, it could be a pasted url or it could be a manually entered url where the user doesn’t feel like typing in http://… I’m working on a URL shortening app.

Advertisement

Answer

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

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

Pattern p = Pattern.compile(URL_REGEX);
Matcher m = p.matcher("example.com");//replace with string to compare
if(m.find()) {
    System.out.println("String contains URL");
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement