title: Regex optimisation - escaping ampersands in java
body: <p>I need to replace all &amp; in a String that isnt part of a HTML entity. So that the String "This &amp; entites <code>&amp;gt;</code> &amp; <code>&amp;lt;</code>" will return "This <code>&amp;amp;</code> entites <code>&amp;gt; &amp;amp; &amp;lt;</code>"</p>
  
  <p>And I've come up with this regex-pattern: "<strong>&amp;[a-zA-Z0-9]{2,7};</strong>" which works fine. 
  But I'm not very skilled in regex, and when I test the speed over 100k iterations, it uses double amount of time over a previous used method, that didnt use regex. (But werent working 100% either).</p>
  
  <p>Testcode:</p>
  
  <pre><code>long time = System.currentTimeMillis();
  String reg = "&amp;(?!&amp;#?[a-zA-Z0-9]{2,7};)";
  String s="a regex test 1 &amp; 2  1&amp;2 and &amp;_gt; - &amp;_lt;"
  for (int i = 0; i &lt; 100000; i++) {test=s.replaceAll(reg, "&amp;amp;");}
  System.out.println("Finished in:" + (System.currentTimeMillis() - time) + " milliseconds");
  </code></pre>
  
  <p>So the question would be whether there is some obvious ways of optimize this regex expression for it to be more effective?</p>