title: Regular expression performance in Java -- better few complex or many simple?
body: <p>I am doing some fairly extensive string manipulations using regular expressions in Java. Currently, I have many blocks of code that look something like:</p>
  
  <pre><code>Matcher m = Pattern.compile("some pattern").matcher(text);
  StringBuilder b = new StringBuilder();
  int prevMatchIx = 0;
  while (m.find()) {
   b.append(text.substring(prevMatchIx, m.start()));
   String matchingText = m.group(); //sometimes group(n)
   //manipulate the matching text
   b.append(matchingText);
   prevMatchIx = m.end();
  }
  text = b.toString()+text.substring(prevMatchIx);
  </code></pre>
  
  <p>My question is which of the two alternatives is more efficient (primarily time, but space to some extent):</p>
  
  <p>1) Keep many existing blocks as above (assuming there isn't a better way to handle such blocks -- I can't use a simple <code>replaceAll()</code> because the groups must be operated on).</p>
  
  <p>2) Consolidate the blocks into one big block. Use a <code>"some pattern"</code> that is the combination of all the old blocks' patterns using the |/alternation operator. Then, use if/else if within the loop to handle each of the matching patterns.</p>
  
  <p>Thank you for your help!</p>