title: Linkify text with regular expressions in Java
body: <p>I have a wysiwyg text area in a Java webapp. Users can input text and style it or paste some already HTML-formatted text.</p>
  
  <p>What I am trying to do is to <em>linkify</em> the text. This means, converting all possible URLs within text, to their "working counterpart", i.e. adding &lt; a href="...">...&lt; /a>.</p>
  
  <p>This solution <strong>works</strong> when all I have is plain text:</p>
  
  <pre><code>String r = "http(s)?://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?";
  Pattern pattern = Pattern.compile(r, Pattern.DOTALL | Pattern.UNIX_LINES | Pattern.CASE_INSENSITIVE);
  Matcher matcher = pattern.matcher(comment);
  comment = matcher.replaceAll("&lt;a href=\"$0\"&gt;$0&lt;/a&gt;"); // group 0 is the whole expression
  </code></pre>
  
  <p>But the problem is when there is some already formatted text, i.e. that it <em>already</em> has the &lt; a href="...">...&lt; /a> tags.</p>
  
  <p>So I am looking for some way for the pattern <em>not to match</em> whenever it finds the text <em>between two HTML tags (&lt; a>)</em>. I have read this can be achieved with <a href="http://www.regular-expressions.info/lookaround.html" rel="nofollow noreferrer">lookahead</a> or <a href="http://www.lexemetech.com/2007/10/zero-width-negative-lookbehind.html" rel="nofollow noreferrer">lookbehind</a> but I still can't make it work. I am sure I am doing it wrong because the regex still matches. And yes, I have been playing around/ debugging groups, changing $0 to $1 etc.</p>
  
  <p>Any ideas?</p>