How can I write a regex in Java that will perform a .replaceFirst on a group that is not in a comment? <p>So I need to return modified String where it replaces the first instance of a token with another token while skipping comments. Here's an example of what I'm talking about:</p> <pre><code>This whole quote is one big String -- I don't want to replace this @@ But I want to replace this @@! </code></pre> <p>Being a former .NET developer, I thought this was easy. I'd just do a negative lookbehind like this:</p> <pre><code>(?&lt;!--.*)@@ </code></pre> <p>But then I learned Java can't do this. So upon learning that the curly braces are okay, I tried this:</p> <pre><code>(?&lt;!--.{0,9001})@@ </code></pre> <p>That didn't throw an exception, but it did match the @@ in the comment.</p> <p>When I test this regex with a Java regex tester, it works as expected. About the only thing I can think of is that I'm using Java 1.5. Is it possible that Java 1.5 has a bug in its regex engine? Assuming it does, how do I get Java 1.5 to do what I want it to do without breaking up my string and reassembling it?</p> <p><strong>EDIT</strong> I changed the # to the -- operator since it looks like the regex will be more complex with two chars instead of one. I originally did not reveal that I was modifying a query in order to avoid off topic discussion on "Well you shouldn't modify queries that way!" I have a very good reason for doing this. Please don't discuss query modification good practices. Thanks</p>