title: How to use python regex to replace using captured group?
body: <p>Suppose I want to change <code>the blue dog and blue cat wore blue hats</code> to <code>the gray dog and gray cat wore blue hats</code>.</p>
  
  <p>With <code>sed</code> I could accomplish this as follows:</p>
  
  <pre><code>$ echo 'the blue dog and blue cat wore blue hats' | sed 's/blue \(dog\|cat\)/gray \1/g'
  </code></pre>
  
  <p>How can I do a similar replacement in Python? I've tried:</p>
  
  <pre><code>&gt;&gt;&gt; import re
  &gt;&gt;&gt; s = "the blue dog and blue cat wore blue hats"
  &gt;&gt;&gt; p = re.compile(r"blue (dog|cat)")
  &gt;&gt;&gt; p.sub('gray \1',s)
  'the gray \x01 and gray \x01 wore blue hats'
  </code></pre>