Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 452
William L. Avatar asked Jun 13 '12 01:06

William L.


People also ask

How check string is URL or not in android?

Use URLUtil to validate the URL as below. It will return True if URL is valid and false if URL is invalid.

How do I check if a string contains a URL?

HTMLInputElement. checkValidity() method is used to check if a string in <input> element's value attribute is URL . The checkvalidity() method returns true if the value is a proper URL and false if the input is not a proper URL.

How do you check if a string contains a in Java?

You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1.


1 Answers

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"); } 
like image 88
Chandra Avatar answered Sep 23 '22 23:09

Chandra