title: parsing nested parentheses in python, grab content by level
body: <p>Apparently this problem comes up fairly often, after reading </p>
  
  <p><a href="https://stackoverflow.com/questions/524548/regular-expression-to-detect-semi-colon-terminated-c-for-while-loops/524624#524624">Regular expression to detect semi-colon terminated C++ for &amp; while loops</a></p>
  
  <p>and thinking about the problem for a while, i wrote a function to return the content contained inside an arbitrary number of nested () </p>
  
  <p>The function could easily be extended to any regular expression object, posting here for your thoughts and considerations.  </p>
  
  <p>any refactoring advice would be appreciated</p>
  
  <p>(note, i'm new to python still, and didn't feel like figuring out how to raise exceptions or whatever, so i just had the function return 'fail' if it couldin't figure out what was going on)</p>
  
  <p>Edited function to take into account comments: </p>
  
  <pre><code>def ParseNestedParen(string, level):
      """
      Return string contained in nested (), indexing i = level
      """
      CountLeft = len(re.findall("\(", string))
      CountRight = len(re.findall("\)", string))
      if CountLeft == CountRight:
          LeftRightIndex = [x for x in zip(
          [Left.start()+1 for Left in re.finditer('\(', string)], 
          reversed([Right.start() for Right in re.finditer('\)', string)]))]
  
      elif CountLeft &gt; CountRight:
          return ParseNestedParen(string + ')', level)
  
      elif CountLeft &lt; CountRight:
          return ParseNestedParen('(' + string, level)
  
      return string[LeftRightIndex[level][0]:LeftRightIndex[level][1]]
  </code></pre>