java - Java 中的正则表达式用于 URL 过滤

标签 java regex

我正在使用以下代码段将纯文本超链接转换为 html url 超链接。

message = message.replaceAll("(?:https?|ftps?|http?)://[\\w/%.\\-?&=]+",
        "<a href='$0' target='_blank'>$0</a>").replaceAll(
        "(www\\.)[\\w/%.\\-?&=]+", "<a href='http://$0' target='_blank'>$0</a>");

但我注意到某些 url 组合无法成功转换为 html 超链接。任何人都可以建议如何改进代码以匹配这些情况吗?

enter image description here

最佳答案

我已经尝试过几次了。想出了一个适用于所有情况的棘手模式,它创建有效 URL,但尾随 / 的情况没有得到很好的处理。希望有人建议快速解决这个问题。

这是代码:

    String s="stackoverflow " +
            "http://naishe.blogspot.com " +
            "http://tw.com/#!/someTEXTs  " +
            "http://ts123t1.rapi.com/#!download|13321|1313|fairy_tale.mp4 " +
            "http://www.google.com/ " +
            "https://www.google.com/. " +
            "google.com " +
            "google.com, " +
            "google.com/test " +
            "123.com/test " +
            "ex-ample.com " +
            "http://ex-ample.com/test-url_chars?param1=val1&;par2=val+with%20spaces " +
            "something else";
    Pattern trimmer = Pattern.compile("(?:\\b(?:http|ftp|www\\.)\\S+\\b)|(?:\\b\\S+\\.com\\S*\\b)");
    Matcher m = trimmer.matcher(s);
    StringBuffer out = new StringBuffer();
    int i = 1;
    System.out.println(trimmer.toString());
    while(m.find()){
        System.out.println("|"+m.group()+"|");
    m.appendReplacement(out, "<a href=\""+m.group()+"\">URL"+ i++ +"</a>");
}
m.appendTail(out);
System.out.println(out+"!");

这是输出

(?:\b(?:http|ftp|www\.)\S+\b)|(?:\b\S+\.com\S*\b)
|http://naishe.blogspot.com|
|http://tw.com/#!/someTEXTs|
|http://ts123t1.rapi.com/#!download|13321|1313|fairy_tale.mp4|
|http://www.google.com|
|https://www.google.com|
|google.com|
|google.com|
|google.com/test|
|123.com/test|
|ex-ample.com|
|http://ex-ample.com/test-url_chars?param1=val1&;par2=val+with%20spaces|

stackoverflow <a href="http://naishe.blogspot.com">URL1</a> 
<a href="http://tw.com/#!/someTEXTs">URL2</a>  
<a href="http://ts123t1.rapi.com/#!download|13321|1313|fairy_tale.mp4">URL3</a>
 <a href="http://www.google.com">URL4</a>/ 
<a href="https://www.google.com">URL5</a>/.
 <a href="google.com">URL6</a> <a href="google.com">URL7</a>,
 <a href="google.com/test">URL8</a> <a href="123.com/test">URL9</a>
 <a href="ex-ample.com">URL10</a>
 <a href="http://ex-ample.com/test-url_chars?param1=val1&;par2=val+with%20spaces">URL11</a> something else!

你看到尾随的/了吗? :)

给OP的友好建议:在提供测试用例时,请选择我们可以复制的格式。无法从 JPEG 复制到文本编辑器。

关于java - Java 中的正则表达式用于 URL 过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9109282/

相关文章:

java - 如何管理数百个插入?

java - Java 程序中的 Unicode 转义行为

java - 格式化 IP :Port string to

java - 使正则表达式更加动态

Java:如何复制目录但排除主目录深处的一些目录

java - Project Reactor - 如何按窗口处理结果

regex - PowerShell Select-String from file with Regex

regex - 获取模式的最后一个实例

regex - Grep 表达式排除了我想要的一些匹配项

python - 正则表达式替换文本之前和之后,保持文本就位