title: bash_rematch and regex (with nested parens)
body: <p>I'm having trouble with a regex, I need search and remove the pattern matching the regex, when found I need to trim out. I wrote a regex like that</p>
  
  <pre><code>regex='(.*)((aa[[:space:]]bb)|(awd)|(bab)|(bc[[:space:]]d))(*.)'
  </code></pre>
  
  <p>in which I define all the beginning (1), the portion in which can be the target (2) and all the ending (3).
  It's easy with simple regex like (.<em>)(abc)(.</em>)
  string="abc"; regex='(<em>.)(abc)(.</em>)'</p>
  
  <pre><code>[[ $string =~ $regex) &amp;&amp; myvar=${BASH_REMATCH[2]} &amp;&amp; buffer=${BASH_REMATCH[1]}${BASH_REMATCH[3]}
  </code></pre>
  
  <p>The trouble begin when I define a regex with nested parens and OR groups, like the first regex posted here.
  This is a sample from my shell:</p>
  
  <pre><code>$ string=" foo bar baz bac"
  $ regex='(.*)((hello[[:space:]]world)|(example)|(funk[[:space:]]you)|(bar[[:space:]]baz))(.*)'
  
  $ [[ $string =~ $regex ]] &amp;&amp; echo ${BASH_REMATCH[1]}
  foo
  $ [[ $string =~ $regex ]] &amp;&amp; echo ${BASH_REMATCH[2]}
  bar baz
  $ [[ $string =~ $regex ]] &amp;&amp; echo ${BASH_REMATCH[3]}
  
  $ [[ $string =~ $regex ]] &amp;&amp; echo ${BASH_REMATCH[4]}
  
  $ [[ $string =~ $regex ]] &amp;&amp; echo ${BASH_REMATCH[5]}
  
  $ [[ $string =~ $regex ]] &amp;&amp; echo ${BASH_REMATCH[6]}
  bar baz
  $ [[ $string =~ $regex ]] &amp;&amp; echo ${BASH_REMATCH[7]}
  bac
  $ [[ $string =~ $regex ]] &amp;&amp; echo ${BASH_REMATCH[@]}
  foo bar baz bac foo bar baz bar baz bac
  </code></pre>
  
  <p>The matching have a strange behaviour, I don't find the other portion of the input string in ${BASH_REMATCH[3]} although is in the 3rd parens of the regex.
  What's happen with nested parens?</p>