Processing a String and replacing al URL's with working links via Java

☆樱花仙子☆ 提交于 2019-12-11 18:36:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!