Java : replacing text URL with clickable HTML link

前端 未结 6 772
不知归路
不知归路 2020-12-20 13:54

I am trying to do some stuff with replacing String containing some URL to a browser compatible linked URL.

My initial String looks like this :

\"hell         


        
6条回答
  •  情话喂你
    2020-12-20 14:22

    Belows code replaces links starting with "http" or "https", links starting just with "www." and finally replaces also email links.

      Pattern httpLinkPattern = Pattern.compile("(http[s]?)://(www\\.)?([\\S&&[^.@]]+)(\\.[\\S&&[^@]]+)");
    
      Pattern wwwLinkPattern = Pattern.compile("(?$0");
    
          final Matcher wwwLinksMatcher = wwwLinkPattern.matcher(textWithHttpLinksEnabled);
          textWithHttpLinksEnabled = wwwLinksMatcher.replaceAll("$0");
    
          final Matcher mailLinksMatcher = mailAddressPattern.matcher(textWithHttpLinksEnabled);
          textWithHttpLinksEnabled = mailLinksMatcher.replaceAll("$0");
    
          System.out.println(textWithHttpLinksEnabled);
        }
    

    Prints:

    ajdhkas www.dasda.pl/asdsad?asd=sd www.absda.pl maiandrze@asdsa.pl klajdld http://dsds.pl httpsda http://www.onet.pl https://www.onsdas.plad/dasda
    

提交回复
热议问题