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
The best way is to to set the property autolink to your textview, Android will recognize, change the appearance and make clickable a link anywhere inside the string.
android:autoLink="web"
This is simply done with a try catch around the constructor (this is necessary either way).
String inputUrl = getInput();
if (!inputUrl.contains("http://"))
inputUrl = "http://" + inputUrl;
URL url;
try {
url = new URL(inputUrl);
} catch (MalformedURLException e) {
Log.v("myApp", "bad url entered");
}
if (url == null)
userEnteredBadUrl();
else
continue();
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");
}
This function is working for me
private boolean containsURL(String content){
String REGEX = "\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
Pattern p = Pattern.compile(REGEX,Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(content);
if(m.find()) {
return true;
}
return false;
}
Call this function
boolean isContain = containsURL("Pass your string here...");
Log.d("Result", String.valueOf(isContain));
NOTE :- I have tested string containing single url