regular expression for getting content between parentheses

Rajanikanth Jammalamadaka rajanikanth at gmail.com
Thu May 7 21:25:39 EDT 2009


Thanks for your replies.

I changed the file to look like this:


{ testName : {"someParam": "value1", "anotherParam": (value2, value3)},
}

to make it look like a hash to Python.

Thanks,

Raj

On Thu, May 7, 2009 at 5:19 PM, Rhodri James
<rhodri at wildebst.demon.co.uk> wrote:
> 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
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Rajanikanth



More information about the Python-list mailing list