title: regex to remove all whitespaces except between brackets
body: <p>I've been wrestling with an issue I was hoping to solve with regex. </p>
  
  <p>Let's say I have a string that can contain any alphanumeric with the possibility of a substring within being surrounded by square brackets. These substrings could appear anywhere in the string like this. There can also be any number of bracket-ed substrings. </p>
  
  <p>Examples:</p>
  
  <ul>
  <li>aaa[bb b]</li>
  <li>aaa[bbb]ccc[d dd]</li>
  <li>[aaa]bbb[c cc]</li>
  </ul>
  
  <p>You can see that there are whitespaces in some of the bracketed substrings, that's fine. My main issue right now is when I encounter spaces outside of the brackets like this:</p>
  
  <ul>
  <li>a aa[bb b]</li>
  </ul>
  
  <p>Now I want to preserve the spaces inside the brackets but remove them everywhere else.</p>
  
  <p>This gets a little more tricky for strings like:</p>
  
  <ul>
  <li>a aa[bb b]c cc[d dd]e ee[f ff]</li>
  </ul>
  
  <p>Here I would want the return to be:</p>
  
  <ul>
  <li>aaa[bb b]ccc[d dd]eee[f ff]</li>
  </ul>
  
  <p>I spent some time now reading through different reg ex pages regarding lookarounds, negative assertions, etc. and it's making my head spin. </p>
  
  <p>NOTE: for anyone visiting this, I was not looking for any solution involving nested brackets. If that was the case I'd probably do it pragmatically like some of the comments mentioned below. </p>