title: Replace all spaces in the key of a property file
body: <p>I would like to escape all keys that contain spaces in a Java properties file by adding a <code>\</code> before them</p>
  
  <p><strong>Example input</strong> </p>
  
  <pre><code>prop with spaces=value with spaces
  #comment should not be replaced 
  prop_without_spaces=value with spaces 2
  </code></pre>
  
  <p><strong>Desired output:</strong></p>
  
  <pre><code>prop\ with\ spaces=value with spaces
  #comment should not be replaced 
  prop_without_spaces=value with spaces 2
  </code></pre>
  
  <p>I know I can replace all spaces with </p>
  
  <pre><code>    &lt;replaceregexp byline="true" flags="g" match="\s" replace="\\\\ " file="..."/&gt;
  </code></pre>
  
  <p>But it renders this result </p>
  
  <pre><code>prop\ with\ spaces=value\ with\ spaces
  #comment\ should\ not\ be\ replaced 
  prop_without_spaces=value\ with\ spaces\ 2
  </code></pre>
  
  <p>Or I can do something like this <code>^(([^=])|(\s))*(=.*)</code> to match the various groups, but then how do I replace all spaces, e.g. how do I reconstruct the result to include only the non spaces? </p>
  
  <p>In other words, given an input as above, how do I do the following pseudo code, in regex: </p>
  
  <ul>
  <li>for rows that don't start with a <code>#</code></li>
  <li>for all chars before the first <code>=</code> sign </li>
  <li>replace all " " (spaces) with a "\ " (forward slash, space)</li>
  </ul>
  
  <p>Is that possible in RegEx in general, and in Java RegEx in particular? (preferably ANT <code>replaceregexp</code> example)</p>
  
  <p><strong>EDIT</strong>: The solution needs to be a RegEx expression, no code can be involved (unfortunately). I know how to solve this using code :) (thanks for the suggestions though), but I'm trying to go for a RegEx solution first (since I'm using ANT, it will require writing a custom task which I try to avoid).</p>
  
  <p><strong>EDIT2</strong> Based on the great answers, here are the working ANT versions:</p>
  
  <p><strong>Using \G</strong></p>
  
  <pre><code>&lt;replaceregexp match="(\\G[^#= ]*) " replace="\1\\\\ " byline="true"... /&gt;
  </code></pre>
  
  <p><strong>Using lookahead</strong> </p>
  
  <p>Escaping comments that have <code>=</code> sign in them</p>
  
  <pre><code>&lt;replaceregexp match="(\s)(?=.*=)" replace="\\\\ " ... /&gt;
  </code></pre>
  
  <p><strong>Using lookahead + lookbehind</strong> </p>
  
  <p>Not escaping comment lines at all (overkill I think)</p>
  
  <pre><code>&lt;replaceregexp match="(?&amp;lt;!#[^=]{0,100})(\s)(?=.*=)" replace="\\\\ " ... /&gt;
  </code></pre>