title: Sed | Variable containing regex causes invalid reference error
body: <p>I'm having problems with sed and the back-referencig when using variables containing regexes.
  It is a parser written in bash. At a very earlier point, I want to use sed to clean every line into the needed data: the indentation, a key and a value (colon separated). The data is similar to yaml but using an equals.
  A basic example of the data:</p>
  
  <pre><code>overview = peparing 2016-10-22
    license= sorted 2015-11-01
  </code></pre>
  
  <p>The function I'm having problems with does the logic in a while loop:</p>
  
  <pre><code>function prepare_parsing () {
    local file=$1
  
    # regex components:
    local s='[[:space:]]*'  \
          w='[a-zA-Z0-9_]*' \
          fs=':'
  
    # regexes(NoQuotes, SingleQuotes, DoubleQuotes):
    local searchNQ='^('$s')('$w')'$s'='$s'(.*)'$s'$'      \
          searchSQ='^('$s')('$w')'$s'='$s\''(.*)'\'$s'\$' \
          searchDQ='^('$s')('$w')'$s'='$s'"(.*)"'$s'\$'   \
          replace="\1$fs\2$fs\3"
  
    while IFS="$fs" read -r indentation key value; do
      ...
      SOME CUSTOM LOGIC
      ...
    done &lt; &lt;(sed -n "s/${searchNQ}/${replace}/p" $file)
  }
  </code></pre>
  
  <p>When trying to call the function, I receive the known invalid reference error into \3:  <code>invalid reference \3 on s' command's RHS</code></p>
  
  <p>To debug this, after the vars definition, I've printed their values using the printf and the %q option.</p>
  
  <pre><code>printf "%q\n" $searchNQ $searchSQ $searchDQ $replace
  </code></pre>
  
  <p>Getting these values:</p>
  
  <pre><code>\^\(\[\[:space:\]\]\*\)\(\[a-zA-Z0-9_\]\*\)\[\[:space:\]\]\*=\[\[:space:\]\]\*\(.\*\)\[\[:space:\]\]\*\$
  \^\(\[\[:space:\]\]\*\)\(\[a-zA-Z0-9_\]\*\)\[\[:space:\]\]\*=\[\[:space:\]\]\*\'\(.\*\)\'\[\[:space:\]\]\*\\\$
  \^\(\[\[:space:\]\]\*\)\(\[a-zA-Z0-9_\]\*\)\[\[:space:\]\]\*=\[\[:space:\]\]\*\"\(.\*\)\"\[\[:space:\]\]\*\\\$
  $'\\1\034\\2\034\\3'
  </code></pre>
  
  <p>And maybe here's the problem, the excessive escape sequences when the shell (bash) expand the variables (for example, it seems to be escaping the *, the [], ...).</p>
  
  <p>If I pass the -r option to sed, it works perfectly, but I have to avoid this since the system that will execute the script won't have this sed implementation: I have to use basic sed.</p>
  
  <p>Do you have any idea on how to store the regex into variables and make them usable for the backreferencing on the RHS?</p>
  
  <p>It works in these two cases:</p>
  
  <p>When using a plain regex string:</p>
  
  <pre><code>sed -n "s/^\([[:space:]]*\)\([a-zA-Z0-9_]*\)[[:space:]]*=[[:space:]]*\(.*\)[[:space:]]*\$/\1:\2:\3/p" $file
  </code></pre>
  
  <p>And when I use just the vars s, w and fs:</p>
  
  <pre><code>sed -n "s/^\($s\)\($w\)$s=$s\(.*\)$s\$/\1$fs\2$fs\3/p" $file
  </code></pre>
  
  <p>Many thanks for the help!</p>