title: Groovy: Idiomatic way to replace captured groups
body: <p>I've a string like this: <code>docker login -u username -p password docker-registry-url</code>.</p>
  
  <p>I execute the command in a Groovy script with <code>execute</code>. For debugging purposes, I print the command before execution, but since it contains sensitive data, I obfuscate the username and password.</p>
  
  <pre><code>def printableCmd = cmd.toString()
  
  def m = printableCmd =~ /(?:.+) -u (.+) -p (.+) (?:.+)/
  
  if (m.matches() &amp;&amp; m[0].size() &gt;= 3) {
    printableCmd = m[0][-1..-2].inject(m[0][0]) { acc, val -&gt; acc.replaceAll(val, "***") }
  }
  </code></pre>
  
  <p>The above works as expected and prints <code>docker login -u *** -p *** docker-registry-url</code>, but I'm wondering if there is a more idiomatic way to do this. Note that I don't want to delete the captured groups, just replace them with asterisks, thus making it very clear that the command is not wrong, but obfuscated for security purposes.</p>