java - 通过 Java 处理字符串并用工作链接替换所有 URL

标签 java url hyperlink anchor transform

如何转换如下文本或任何其他包含 URL 的文本(http ftp 等)

Go to this link http://www.google.com (ofc stack overflow already does this, on my website this is just plain text);

进入此

Go to this link <a href="http://www.google.com">www.google.com</a>

我想出了这个方法

public String transformURLIntoLinks(String text){
    String urlValidationRegex = "(https?|ftp)://(www\\d?|[a-zA-Z0-9]+)?.[a-zA-Z0-9-]+(\\:|.)([a-zA-Z0-9.]+|(\\d+)?)([/?:].*)?";
    Pattern p = Pattern.compile(urlValidationRegex);
    Matcher m = p.matcher(text);
    StringBuffer sb = new StringBuffer();
    while(m.find()){
        String found =m.group(1); //this String is only made of the http or ftp (just the first part of the link)
        m.appendReplacement(sb, "<a href='"+found+"'>"+found+"</a>"); // the result would be <a href="http">"http"</a>
    }
    m.appendTail(sb);
    return sb.toString();
}

问题是我尝试过的正则表达式仅匹配第一部分(“http”或“ftp”)。

我的输出变成:Go to this link <a href='http'>http</a>

应该是这个

Go to this link <a href='http://www.google.com'>http://www.google.com</a>

最佳答案

public String transformURLIntoLinks(String text){
String urlValidationRegex = "(https?|ftp)://(www\\d?|[a-zA-Z0-9]+)?.[a-zA-Z0-9-]+(\\:|.)([a-zA-Z0-9.]+|(\\d+)?)([/?:].*)?";
Pattern p = Pattern.compile(urlValidationRegex);
Matcher m = p.matcher(text);
StringBuffer sb = new StringBuffer();
while(m.find()){
    String found =m.group(0); 
    m.appendReplacement(sb, "<a href='"+found+"'>"+found+"</a>"); 
}
m.appendTail(sb);
return sb.toString();
   }

m.group(1) 是错误的。 m.group(0) 有效。 这会将文本中找到的任何 URL 转换为 anchor 。

关于java - 通过 Java 处理字符串并用工作链接替换所有 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17672451/

相关文章:

Java通过浏览器导出Excel

JQuery - 从 URL 获取变量以设置 CSS 值

json - 从 json 字符串构建 url 时,Alamofire 返回无效的 url

url - Kubernetes 中的端点 URL 管理

html - 超链接到 Excel 单元格

html - 在悬停 div 时更改链接的颜色

Java8 安全 WebSocket 握手问题(Tyrus 和 Jetty)

java - 快速关键速率管理我的 Java Swing 应用程序,如何在管道中尽早删除事件?

java - 使用 OutputStream/InputStream 的加密和 HMAC(基于流的加密然后 MAC)

html - 在新选项卡中打开链接而不单击链接