【发布时间】:2018-08-31 17:35:57
【问题描述】:
我必须将以纯文本输入的 url 转换为 html href,我想找到多个 url。
这个:
Hi here is a link for you: http://www.google.com. Hope it works.
将成为:
Hi here is a link for you: <a href='http://www.google.com'>http://www.google.com</a>. Hope it works.
找到这个代码:
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();
}
张贴在这里https://stackoverflow.com/a/17704902
而且效果很好。对于所有以http 为前缀的网址。
但我也想找到以www 开头的网址。
知道他的正则表达式的任何人都可以帮助我吗?
【问题讨论】:
-
尝试以
(?:(https?|ftp):\/\/)?开始您的正则表达式,它将与仅以www开头的url 匹配