如何转换如下文本或任何其他包含 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/