Convert Plain Text Links to HREF Using Regular Expressions
Published: 16 Jul 2009
For a project I was working on recently I had snippets of plain text with links embedded but without the actual HTML code. Here’s some code to get the job done:
1 public String getDescriptionForWeb() {
2 if (this.description == null) return null;
3 String r = "(?<!href=)http(s)?://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?";
4 Pattern pattern = Pattern.compile(r, Pattern.DOTALL | Pattern.UNIX_LINES | Pattern.CASE_INSENSITIVE);
5 Matcher matcher = pattern.matcher(this.description);
6 return matcher.replaceAll("<a href=\"$0\">$0</a>");
7 }
blog comments powered by Disqus