title: Need the Groovy way to do partial file substitutions
body: <p>I have a file that I need to modify.  The part I need to modify (not the entire file), is similar to the properties shown below.  The problem is that I only need to replace part of the "value", the "ConfigurablePart" if you will.  I receive this file so can not control it's format.</p>
  
  <pre><code>alpha.beta.gamma.1 = constantPart1ConfigurablePart1
  alpha.beta.gamma.2 = constantPart2ConfigurablePart2
  alpha.beta.gamma.3 = constantPart3ConfigurablePart3
  </code></pre>
  
  <p>I made this work this way, though I know it is really bad! </p>
  
  <pre><code>def updateFile(String pattern, String updatedValue) {
      def myFile = new File(".", "inputs/fileInherited.txt")
      StringBuffer updatedFileText = new StringBuffer()
      def ls = System.getProperty('line.separator')
      myFile.eachLine{ line -&gt;
          def regex = Pattern.compile(/$pattern/)
          def m = (line =~ regex)
          if (m.matches()) {
              def buf = new StringBuffer(line)
              buf.replace(m.start(1), m.end(1), updatedValue)
              line = buf.toString()
          }
          println line
          updatedFileText.append(line).append(ls)
      }
      myFile.write(updatedFileText.toString())
  }
  </code></pre>
  
  <p>The passed in pattern is required to contain a group that is substituted in the StringBuffer.  Does anyone know how this should really be done in Groovy?  </p>
  
  <p><strong>EDIT -- to define the expected output</strong></p>
  
  <p>The file that contains the example lines needs to be updated such that the "ConfigurablePart" of each line is replaced with the updated text provided.  For my ugly solution, I would need to call the method 3 times, once to replace ConfigurablePart1, once for ConfigurablePart2, and finally for ConfigurablePart3.  There is likely a better approach to this too!!!</p>
  
  <p>*<strong><em>UPDATED -- Answer that did what I really needed *</em></strong></p>
  
  <p>In case others ever hit a similar issue, the groovy code improvements I asked about are best reflected in the accepted answer.  However, for my problem that did not quite solve my issues.  As I needed to substitute only a portion of the matched lines, I needed to use back-references and groups.  The only way I could make this work was to define a three-part regEx like:</p>
  
  <pre><code>(.*)(matchThisPart)(.*)
  </code></pre>
  
  <p>Once that was done, I was able to use:</p>
  
  <pre><code>it.replaceAdd(~/$pattern/, "\$1$replacement\$3")
  </code></pre>
  
  <p>Thanks to both replies - each helped me out a lot!</p>