title: Replacing partial regex matches in place with Ruby
body: <p>I want to transform the following text</p>
  
  <pre><code>This is a ![foto](foto.jpeg), here is another ![foto](foto.png)
  </code></pre>
  
  <p>into</p>
  
  <pre><code>This is a ![foto](/folder1/foto.jpeg), here is another ![foto](/folder2/foto.png)
  </code></pre>
  
  <p>In other words I want to find all the image paths that are enclosed between brackets (the text is in Markdown syntax) and replace them with other paths. The string containing the new path is returned by a separate <code>real_path</code> function.</p>
  
  <p>I would like to do this using <code>String#gsub</code> in its block version. Currently my code looks like this:</p>
  
  <pre><code>re = /!\[.*?\]\((.*?)\)/
  
  rel_content = content.gsub(re) do |path|
      real_path(path)
  end
  </code></pre>
  
  <p>The problem with this regex is that it will match <code>![foto](foto.jpeg)</code> instead of just <code>foto.jpeg</code>. I also tried other regexen like <code>(?&gt;\!\[.*?\]\()(.*?)(?&gt;\))</code> but to no avail.</p>
  
  <p>My current workaround is to split the path and reassemble it later.</p>
  
  <p>Is there a Ruby regex that matches only the path inside the brackets and not all the contextual required characters?</p>
  
  <p><strong>Post-answers update</strong>: The main problem here is that Ruby's regexen have no way to specify zero-width lookbehinds. The most generic solution is to group what the part of regexp before and the one after the real matching part, i.e. <code>/(pre)(matching-part)(post)/</code>, and reconstruct the full string afterwards.</p>
  
  <p>In this case the solution would be</p>
  
  <pre><code>re = /(!\[.*?\]\()(.*?)(\))/
  
  rel_content = content.gsub(re) do
      $1 + real_path($2) + $3
  end
  </code></pre>