title: Using backslashes in Groovy
body: <p>I'm using groovy to write a script that replaces UNC server names and a part of the directory structure.  I have the following:</p>
  
  <pre><code>def patternToFind = /\\\\([a-zA-Z0-9-]+)\\share\\([a-zA-Z]+)/
  def patternToReplace = '\\\\\\\\SHARESERVER\\\\share\\\\OPS'
  </code></pre>
  
  <p>This works, but all those \'s are pretty ugly.  I understand in the regex why <code>\\\\</code> is used to find <code>\\</code>, but what is confusing me is why in the replacement I'm doing I have to use four <code>\</code>'s to equal one <code>\</code>.</p>
  
  <p>If anyone has a nicer way to do this I would greatly appreciate it.  The goal is to replace </p>
  
  <p><code>\\&lt;server&gt;\share\&lt;env&gt;</code> </p>
  
  <p>with the correct value for <code>&lt;server&gt;</code> and <code>&lt;env&gt;</code></p>
  
  <p>Thanks!</p>
  
  <p>EDIT:  I guess I should clarify.  SHARESERVER and OPS are actually variables.  So truly the end result would be something like:</p>
  
  <pre><code>def serverName = //some passed in server
  def env = //some passed in env
  
  def patternToFind = /\\\\([a-zA-Z0-9-]+)\\NAS\\([a-zA-Z]+)/
  def patternToReplace = '\\\\\\\\' + serverName + '\\\\share\\\\' + env
  </code></pre>
  
  <p>So the only way I think of doing it is building a string literal to replace the section I'm looking for with.  </p>
  
  <p>And I'll be the first to admit that I suck at reg ex, so if you can use them to capture a value in a string and replace just that value with another, I'm all ears.</p>