title: Ruby Regular Expression lookahead to Split at pipe unless contained in brackets
body: <p>I'm trying to decode the following string:</p>
  
  <pre><code>body = '{type:paragaph|class:red|content:[class:intro|body:This is the introduction paragraph.][body:This is the second paragraph.]}'
  body &lt;&lt; '{type:image|class:grid|content:[id:1|title:image1][id:2|title:image2][id:3|title:image3]}'
  </code></pre>
  
  <p>I need the string to split at the pipes but not where a pipe is contained with square brackets, to do this I think I need to perform a lookahead as described here: <a href="https://stackoverflow.com/questions/732029/how-to-split-string-by-unless-is-within-brackets-using-regex">How to split string by &#39;,&#39; unless &#39;,&#39; is within brackets using Regex?</a></p>
  
  <p>My attempt(still splits at every pipe):</p>
  
  <pre><code>x = self.body.scan(/\{(.*?)\}/).map {|m| m[0].split(/ *\|(?!\]) */)}
  -&gt;
  [
    ["type:paragaph", "class:red", "content:[class:intro", "body:This is the introduction paragraph.][body:This is the second paragraph.]"]
    ["type:image", "class:grid", "content:[id:1", "title:image1][id:2", "title:image2][id:3", "title:image3]"]
  ]
  </code></pre>
  
  <p>Expecting:</p>
  
  <pre><code>   -&gt;
      [
        ["type:paragaph", "class:red", "content:[class:intro|body:This is the introduction paragraph.][body:This is the second paragraph.]"]
        ["type:image", "class:grid", "content:[id:1|title:image1][id:2|title:image2][id:3|title:image3]"]
      ]
  </code></pre>
  
  <hr>
  
  <p>Does anyone know the regex required here?</p>
  
  <p>Is it possible to match this regex? I can't seem to modify it correctly <a href="https://stackoverflow.com/questions/678316/regular-expression-to-match-underscores-not-surrounded-by-brackets">Regular Expression to match underscores not surrounded by brackets?</a></p>
  
  <hr>
  
  <p>I modified the answer here <a href="https://stackoverflow.com/questions/2015826/split-string-in-ruby-ignoring-contents-of-parentheses">Split string in Ruby, ignoring contents of parentheses?</a> to get:</p>
  
  <pre><code> self.body.scan(/\{(.*?)\}/).map {|m| m[0].split(/\|\s*(?=[^\[\]]*(?:\[|$))/)}
  </code></pre>
  
  <p>Seems to do the trick. Though I'm sure if there's any shortfalls.</p>