【问题标题】:Detect and convert URL in String Java, Is regex better or even faster?在 String Java 中检测和转换 URL,正则表达式更好还是更快?
【发布时间】:2010-11-17 06:18:17
【问题描述】:

下面的代码检测并转换字符串中的 url。有没有更快或更优雅的方式来完成这段代码?:

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());
            rtn = StringUtils.replace(rtn, item, "<a rel=\"nofollow\" href=\"" + link + "\">" + link + "</a> ");
        } catch (MalformedURLException ignore) {
        }
    return rtn;
}

【问题讨论】:

  • 除了速度和优雅方面的考虑之外,此代码也不会检测括号中的 URL,例如 [1][http://www.google.com/]
  • 你在哪里取字符串文本?是长还是短?

标签: java regex string url


【解决方案1】:

我想我会使用正则表达式,例如:

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;
}

我刚刚从这个有用的正则表达式站点中获取了那个正则表达式:

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

一个快速的谷歌搜索将产生许多正则表达式资源:

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

根据您的使用情况,您可能需要稍微调整一下正则表达式以在开头或结尾修剪内容。

【讨论】:

  • 至少将p 设为类变量。在每个方法调用上一次又一次地编译相同的代码是相当昂贵的。
  • 我自己从来没有做过任何性能测试,不过做一些测试会很容易(只需几分钟)。正如 BalusC 所说,只编译一次。至于复杂性,这是一个艰难的问题。正则表达式可能会变得丑陋。规则始终是从简单开始,然后一次构建更复杂的部分。您可能会考虑尝试多个正则表达式来缓解这种情况(一个寻找 IPv4,另一个寻找 IPv6,等等),我不确定它会有多少性能权衡,但您可以尝试运行几个 10,000 个循环测试只需几分钟即可看到。如果您也进行这些测试,请告诉我们。
  • 如今 CPU 通常是一种相当便宜的商品,因此对于整个项目来说,为了正确性和健壮性而编写代码通常比试图节省每个 CPU 周期更好。我通常建议先以最容易理解、扩展和调试的方式进行操作,分析您的应用程序,并且仅当您发现这些方法占用过多 CPU 时,然后再返回并重新处理它们以提高速度。跨度>
猜你喜欢
  • 1970-01-01
  • 2022-12-31
  • 1970-01-01
  • 2018-10-06
  • 2011-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-31
相关资源
最近更新 更多