What is a good way of detecting urls in a string text?
hi all i have a string text that may contains urls (this text is got from a form text area) and i want to detect those urls and surrounds them with the tag so that they will be represented in html开发者_运维问答 page as links what is the best way of doing that ?
use regular expressions.
(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))
look here from more information http://daringfireball.net/2010/07/improved_regex_for_matching_urls
public boolean isURL(String s){
return s.matches(" (?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'\".,<>?«»\“\”\‘\’]))");
}
It's a complex issue that is difficult to get right, mainly because there are a lot of characters that are valid in URLs that you don't often see in them.
http://www.codinghorror.com/blog/2008/10/the-problem-with-urls.html
Edit: The daringfireball.net link takes some of this into account but you can read about the tradeoffs in the blog post.
精彩评论