regular expression for getting content between parentheses

Rhodri James rhodri at wildebst.demon.co.uk
Thu May 7 20:19:21 EDT 2009


On Fri, 08 May 2009 00:51:14 +0100, Rajanikanth Jammalamadaka  
<rajanikanth at gmail.com> wrote:

> Hi
>
> I have a text file as follows:
>
> testName = (
>  someParam = value1
>  anotherParam = (value2, value3)
> )
>
> how do I write a regular expression to get all the contents of the
> file which are between the first and last parentheses.

You don't, or at least you don't without some cast-iron guarantees
that your file will look *exactly* like this.  If you can guarantee
that, then this should work:

import re

f = open(filename)
data = f.read()
m = re.match(r"""[^(]*\(     # Find the first open parenthesis
                  (.*)        # Gobble up everything...
                  \)[^)]*$    # ...to the last close paren""",
              data, re.X)
if m:
   print m.group(1)


Notice that this will do *exactly* what you asked; pick up
everything between the first and the last parentheses.  In
particular, if your text looks like this:

testName1 = (
   someParam1 = value1
   anotherParam1 = (value2, value3)
)
testName2 = (
   sameParam2 = value4
)

...then what you'll get out is:

   someParam1 = value1
   anotherParam1 = (value2, value3)
)
testName2 = (
   sameParam2 = value4


You can't get around that with regular expressions, you'll
have to parse your way through the input string counting
open and close parentheses as you go.

-- 
Rhodri James *-* Wildebeeste Herder to the Masses



More information about the Python-list mailing list