title: Replace multiple capture groups using regexp with java
body: <p>I have this requirement - for an input string such as the one shown below</p>
  
  <pre><code>8This8 is &amp;reallly&amp; a #test# of %repl%acing% %mul%tiple 9matched9 9pairs
  </code></pre>
  
  <p>I would like to strip the matched word boundaries (where the matching pair is 8 or &amp; or % etc) and will result in the following</p>
  
  <pre><code>This is really a test of repl%acing %mul%tiple matched 9pairs
  </code></pre>
  
  <p>This list of characters that is used for the pairs can vary e.g. 8,9,%,# etc and only the words matching the start and end with each type will be stripped of those characters, with the same character embedded in the word remaining where it is.</p>
  
  <p>Using <em>Java</em> I can do a pattern as <code>\\b8([^\\s]*)8\\b</code> and replacement as $1, to capture and replace all occurrences of 8...8, but how do I do this for all the types of pairs?</p>
  
  <p>I can provide a pattern such as <code>\\b8([^\\s]*)8\\b|\\b9([^\\s]*)9\\b</code> .. and so on that will match all types of matching pairs *8,9,..), but how do I specify a 'variable' replacement group - </p>
  
  <p>e.g. if  the match is 9...9, the the replacement should be $2.</p>
  
  <p>I can of course run it through multiple of these, each replacing a specific type of pair, but I am wondering if there is a more elegant way.</p>
  
  <p>Or is there a completely different way of approaching this problem?</p>
  
  <p>Thanks.</p>