What's the best way to check if a String contains a URL in Java/Android?
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 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();
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 3986
private static final Pattern 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 part
for( 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 + " ");
}
}