问题
How would I transform a text like the following or any other text containing an URL (http ftp etc)
Go to this link http://www.google.com (ofc stack overflow already does this, on my website this is just plain text);
Into this
Go to this link
<a href="http://www.google.com">www.google.com</a>
I've come up with this method
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();
}
The problem is the regexes i've tried match only the first part("http" or "ftp").
My output becomes: Go to this link <a href='http'>http</a>
It should be this
Go to this link <a href='http://www.google.com'>http://www.google.com</a>
回答1:
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) was the mistake. m.group(0) works. This will transform any URL found in the text into an anchor.
来源:https://stackoverflow.com/questions/17672451/processing-a-string-and-replacing-al-urls-with-working-links-via-java