title: How do I find the position of matching parentheses or braces in a given piece of text?
body: <p>A lot of text editors and IDEs have a feature that highlights matching parentheses, square brackets, or curly braces when the cursor is placed over either the opening or closing character in one of these pairs.</p>
  
  <p>What algorithm is used to find the position of the matching parenthesis, given the position of either an opening or closing parenthesis in a text file?  Keep in mind that these characters can be nested, so simply scanning forward or backward through the text until you find the opposite character is insufficient.</p>
  
  <p><strong>Example:</strong></p>
  
  <p>I recently ran into this problem when writing a <a href="http://en.wikipedia.org/wiki/Brainfuck">brainf*ck</a> interpreter in Java.  <code>[</code> and <code>]</code> in that language are analogous to a while loop, and can be nested.  The interpreter needs to find the matching <code>[</code> or <code>]</code> depending on the value at the data pointer.  See the <a href="http://en.wikipedia.org/wiki/Brainfuck#ROT13">ROT13 example code</a> for an illustration of nesting.</p>