开发者

Detect and convert URL in String Java, Is regex better or even faster?

开发者 https://www.devze.com 2023-01-25 17:55 出处:网络
The bellow code detects and converts urls in String. Is there faster way or more elegant way to do this block of code?:

The bellow code detects and converts urls in String. Is there faster way or more elegant way to do this block of code?:

public static String detectAndConvertURLs(String text) {
    String[] parts = text.split("\\s");
    String rtn = text;
    for (String item : parts)
        try {
          // adjustment based one of the answers 
          Pattern p = Pattern.compile("((mailto\\:|(news|(ht|f)tp(s?))\\://){1}\\S+)");
          Matcher m = p.matcher(item);
          if( m.matches() ) item = m.group(1);

            URL url = new URL(item);
            String link = url.getProtocol() + "://" + url.getHost() + "/" + (url.getPath() == null ? "" : url.getPath()) + (url.getQuery() == null ? "" : "?" + url.getQuery());
开发者_如何学Python            rtn = StringUtils.replace(rtn, item, "<a rel=\"nofollow\" href=\"" + link + "\">" + link + "</a> ");
        } catch (MalformedURLException ignore) {
        }
    return rtn;
}


I think I would use regular expressions such as:

public static String detectAndConvertURLs(String text) {
   //Regex pattern (unescaped), matches any Internet URL: 
   //((mailto\:|(news|(ht|f)tp(s?))\://){1}\S+)
   Pattern p = Pattern.compile( "((mailto\\:|(news|(ht|f)tp(s?))\\://){1}\\S+)" );
   Matcher m = p.matcher( text );
   if( m.matches() ){
      return m.group(1);
   }else return null;
}

I just took that regex from this site of useful regex expressions:

http://regexlib.com/Search.aspx?k=URL

A quick google search will produce many regex expression resources:

http://www.google.com/search?q=regex+match+url&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a

You might have to massage the regex a little to trim stuff at the beginning or end depending on your use.

0

精彩评论

暂无评论...
验证码 换一张
取 消