如何检测字符串中URL的存在

Rak*_*h N 28 java url

我有一个输入字符串说Please go to http://stackoverflow.com.检测到String的url部分,并且<a href=""></a>许多浏览器/ IDE /应用程序自动添加锚点.所以它变成了Please go to <a href='http://stackoverflow.com'>http://stackoverflow.com</a>.

我需要使用Java做同样的事情.

Osc*_*Ryz 58

使用java.net.URL!

嘿,为什么不在java中使用核心类来获取这个"java.net.URL"并让它验证URL.

虽然以下代码违反了黄金原则"仅针对异常条件使用异常",但尝试重新发明轮子以获得在Java平台上成熟的东西是没有意义的.

这是代码:

import java.net.URL;
import java.net.MalformedURLException;

// Replaces URLs with html hrefs codes
public class URLInString {
    public static void main(String[] args) {
        String s = args[0];
        // separate input by spaces ( URLs don't have spaces )
        String [] parts = s.split("\\s+");

        // Attempt to convert each item into an URL.   
        for( String item : parts ) try {
            URL url = new URL(item);
            // If possible then replace with anchor...
            System.out.print("<a href=\"" + url + "\">"+ url + "</a> " );    
        } catch (MalformedURLException e) {
            // If there was an URL that was not it!...
            System.out.print( item + " " );
        }

        System.out.println();
    }
}
Run Code Online (Sandbox Code Playgroud)

使用以下输入:

"Please go to http://stackoverflow.com and then mailto:oscarreyes@wordpress.com to download a file from    ftp://user:pass@someserver/someFile.txt"
Run Code Online (Sandbox Code Playgroud)

产生以下输出:

Please go to <a href="http://stackoverflow.com">http://stackoverflow.com</a> and then <a href="mailto:oscarreyes@wordpress.com">mailto:oscarreyes@wordpress.com</a> to download a file from    <a href="ftp://user:pass@someserver/someFile.txt">ftp://user:pass@someserver/someFile.txt</a>
Run Code Online (Sandbox Code Playgroud)

当然,可以以不同方式处理不同的协议.例如,您可以使用URL类的getter获取所有信息

 url.getProtocol();
Run Code Online (Sandbox Code Playgroud)

或者其他属性:spec,port,file,query,ref等

http://java.sun.com/javase/6/docs/api/java/net/URL.html

处理所有协议(至少所有java平台都知道的协议)并作为额外的好处,如果有任何java当前无法识别的URL并最终被合并到URL类中(通过库更新),您将获得它透明!

  • 我喜欢Jeff Atwoods专门针对java的文章,因为你根本不需要处理正则表达式.但他的文章*确实*对于经常嵌入括号等内容的URL有好处.组合将非常有效. (2认同)
  • 我刚才知道,URL类已损坏:http://www.youtube.com/watch?v = wDN_EYUvUq0 (2认同)

Mic*_*urr 14

虽然它不是特定于Java的,但Jeff Atwood最近发布了一篇文章,介绍了在尝试查找和匹配任意文本中的URL时可能遇到的陷阱:

网址问题

它提供了一个很好的正则表达式,可以与您需要用来正确(或多或少)处理parens的代码片段一起使用.

正则表达式:

\(?\bhttp://[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|]
Run Code Online (Sandbox Code Playgroud)

帕伦清理:

if (s.StartsWith("(") && s.EndsWith(")"))
{
    return s.Substring(1, s.Length - 2);
}
Run Code Online (Sandbox Code Playgroud)


Jas*_*oco 5

你可以做这样的事情(调整正则表达式以满足你的需要):

String originalString = "Please go to http://www.stackoverflow.com";
String newString = originalString.replaceAll("http://.+?(com|net|org)/{0,1}", "<a href=\"$0\">$0</a>");
Run Code Online (Sandbox Code Playgroud)