title: Remove all unnecessary spaces and a certain punctuation
body: <p>Consider the following string</p>
  
  <pre><code>str1 &lt;- "  say    wut      ??   "
  </code></pre>
  
  <p>I want to remove all additional spaces between words and <code>??</code> and trim the whole thing</p>
  
  <p>So the following works perfectly</p>
  
  <pre><code>gsub("(^ *)|( +(?= ))|( $)", "", str1, perl = TRUE)
  ## [1] "say wut ??"
  </code></pre>
  
  <p>Now, if I have the following string</p>
  
  <pre><code>str2 &lt;- "[ ] say[]    wut      ??  [] "
  </code></pre>
  
  <p>And I want to reach the previous result (I <em>don't</em> want to remove all punctuation except <code>??</code>, because in real life I have other punctuation too that I want to keep. In other words, I just want to remove <code>[]</code> and the unnecessary spaces)</p>
  
  <p>So I've tried the following, but I've got my leading spaces back</p>
  
  <pre><code>gsub("\\]|\\[|(^ *)|( +(?= ))|( $)", "", str2, perl = TRUE)
  ## [1] "  say wut ?? "
  </code></pre>
  
  <p>Interestingly (or not), when reversing the regex order, everything messes up even more</p>
  
  <pre><code>gsub("(^ *)|\\]|\\[|( +(?= ))|( $)", "", str2, perl = TRUE)
  ## [1] "[  say wut ?? "
  </code></pre>
  
  <hr>
  
  <p>Edit: It seems that I wasn't clear enough, but I'm looking for a <em>clean regex</em> solution. I'm well aware that you can do practically <em>anything</em> in several steps (and I'm already doing so), but this is not what I'm looking for.</p>
  
  <p>This is what I was using until now (two steps solution):</p>
  
  <pre><code>gsub("(^ *)|( +(?= ))|( $)", "", gsub("\\]|\\[", "", x), perl = TRUE)
  </code></pre>