处理字符串并替换al URL';通过Java提供工作链接的s
如何转换以下文本或任何其他包含URL的文本(http ftp等) 转到这个链接(ofc堆栈溢出已经这样做了,在我的网站上这只是纯文本) 进入这个 转到此链接处理字符串并替换al URL';通过Java提供工作链接的s,java,url,hyperlink,anchor,transform,Java,Url,Hyperlink,Anchor,Transform,如何转换以下文本或任何其他包含URL的文本(http ftp等) 转到这个链接(ofc堆栈溢出已经这样做了,在我的网站上这只是纯文本) 进入这个 转到此链接 我想出了这个方法 public String transformURLIntoLinks(String text){ String urlValidationRegex = "(https?|ftp)://(www\\d?|[a-zA-Z0-9]+)?.[a-zA-Z0-9-]+(\\:|.)([a-zA-Z0-9.]+|(\\d+
我想出了这个方法
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();
}
public String transformURLIntoLinks(字符串文本){
字符串urlValidationRegex=“(https?| ftp):/(www\\d?[a-zA-Z0-9]+)。[a-zA-Z0-9-]+(\\:)([a-zA-Z0-9.]+(\\d+)([/?:])”;
Pattern p=Pattern.compile(urlvalidateregex);
匹配器m=p.Matcher(文本);
StringBuffer sb=新的StringBuffer();
while(m.find()){
String found=m.group(1);//此字符串仅由http或ftp组成(仅为链接的第一部分)
m、 appendReplacement(sb,“”;//结果为
}
m、 (某人);
使某人返回字符串();
}
问题是我尝试过的正则表达式只匹配第一部分(“http”或“ftp”)
我的输出变成:转到此链接
应该是这样
转到此链接
公共字符串转换URL链接(字符串文本){
字符串urlValidationRegex=“(https?| ftp):/(www\\d?[a-zA-Z0-9]+)。[a-zA-Z0-9-]+(\\:)([a-zA-Z0-9.]+(\\d+)([/?:])”;
Pattern p=Pattern.compile(urlvalidateregex);
匹配器m=p.Matcher(文本);
StringBuffer sb=新的StringBuffer();
while(m.find()){
找到的字符串=m.group(0);
m、 (b)以“”号填列;
}
m、 (某人);
使某人返回字符串();
}
m、 第(1)组是错误的。m、 第(0)组工作。
这会将文本中找到的任何URL转换为锚。不幸的是,这不是编码服务。如果你自己尝试了一些不起作用的东西,回来寻求帮助。但不要要求我们解决您的工作。简单:
publicstringtransformurlintolinks(stringtext){return“转到这个链接”;}
它必须将任何包含URL的文本转换为包含URL锚定的相同文本。我已重新编写了问题并提供了尝试性的解决方案。我找到了解决方案。此解决方案不适用于字符串中有多个链接的情况。
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();
}