title: Getting the "context" text of a matched group
body: <p>I'm using the Matcher class of Java to get some strings, now when I get my matches, I also find their begin index and end index. Now what I want to do is get the <strong>x</strong> preceding and proceeding characters.</p>
  
  <p>So what I did was just call the substring method on  the string with <code>{begin index minus</code><strong>x</strong><code>}</code> to <code>{end index plus</code><strong>x</strong><code>}</code>, but it seems to be a little heavy, for every match, I'll have to loop the string for it's context.</p>
  
  <p>I wanted to know whether there's a better way to do that.</p>
  
  <p>Here is what I've done so far:
  The part that bothers me is the <code>text.substring</code>, how expensive is it</p>
  
  <pre><code>    String text = "Some 22 text with 44 characters";
      Matcher matcher = Pattern.compile("\\d{2}").matcher(text);
      int x = 5;
      while (matcher.find()) {
          String match = matcher.group();
          int start = matcher.start();
          int end = matcher.end();
          String pretext = text.substring(start - x, start);
          String postext = text.substring(end, end + x);
          System.out.println(pretext + " - " + match + " - " + postext);
      }
  </code></pre>
  
  <p>Suggested answer of using grouping to solve this:
  using the <code>regex (.{5})(\d{2}(.{5})</code>.
  First of all, this wouldn't be able to captures ones without at least 5 characters before it. So the solution to that is <code>(.{0,5})(\d{2})(.{0.5})</code>, very nice for that simple regex <code>(\d{2})</code>but for one like "<code>c?at</code>" and the given text "cat" this would match the groups</p>
  
  <ol>
  <li>c</li>
  <li>at</li>
  <li>&nbsp;</li>
  </ol>