title: Why does sed's regex grouping differ from normal regex?
body: <p>I'm struggling to understand why is sed messing up a simple regular expression.</p>
  <p>I've got the following input inside a file called <code>test</code>:</p>
  <pre><code>dbname=example user=example password=1234
  </code></pre>
  <p>And the following regular expression:</p>
  <pre><code>(dbname=)[^\s]+
  </code></pre>
  <p>And I want to replace <code>dbname=example</code> with, say, <code>dbname=dovecot</code>, but without knowing the value of <code>dbname</code> beforehand. To do so, I understand I should do:</p>
  <pre class="lang-sh prettyprint-override"><code>sed -E &quot;s;(dbname=)[^\\s]+;\1dovecot;g test&quot;
  </code></pre>
  <p>However, I get <code>dbname=dovecotser=example password=1234</code> instead of <code>dbname=dovecot user=example password=1234</code>.</p>
  <p>So, to try and understand sed's logic I simplified the input to:</p>
  <pre><code>dbname=example user=example
  </code></pre>
  <p>And I modified my regex so I could see what was going on with the groups. The following regular expression should match <code>dbname=</code> as <code>\1</code>, <code>example</code> as <code>\2</code>, <code> </code> as <code>\3</code> and <code>user=example</code> as <code>\4</code>:</p>
  <pre><code>(dbname=)([^\s]+)([\s]+)([^\s]+)
  </code></pre>
  <p>And it does, at least when using common sense and <a href="https://regex101.com/" rel="nofollow noreferrer">Regex101</a>, for instance.</p>
  <p>Therefore, why is sed returning <code>dbname=</code> as <code>\1</code>, which is correct, but <code>example u</code> as <code>\2</code>, <code>s</code> as <code>\3</code> and <code>er=example</code> as <code>\4</code> when running the following?</p>
  <pre><code>$ sed -E &quot;s;(dbname=)([^\\s]+)([\\s]+)([^\\s]+);\1;g&quot; test
  dbname=
  $ sed -E &quot;s;(dbname=)([^\\s]+)([\\s]+)([^\\s]+);\2;g&quot; test
  example u
  $ sed -E &quot;s;(dbname=)([^\\s]+)([\\s]+)([^\\s]+);\3;g&quot; test
  s
  $ sed -E &quot;s;(dbname=)([^\\s]+)([\\s]+)([^\\s]+);\4;g&quot; test
  er=example
  </code></pre>
  <p>Did I do anything wrong? Is sed using a different approach to regular expressions I don't know of?</p>
  <p>Many thanks.</p>
  <p><em>Note: I'm using <code>;</code> as sed's delimiter for clarity.</em></p>