Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Re: regular expression for getting content between parentheses

12 views
Skip to first unread message

Emile van Sebille

unread,
May 7, 2009, 8:14:59 PM5/7/09
to pytho...@python.org
On 5/7/2009 4:51 PM Rajanikanth Jammalamadaka said...
> 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.
>
> In this case, I want:
>
> someParam = value1
> anotherParam = (value2, value3)
>
> Thanks,

It's not a regex nor probably what you want, but I'd start with...


>>> filetext = '''testName = (
... someParam = value1
... anotherParam = (value2, value3)
... )'''
>>>
>>> print filetext.split("(",1)[-1].rsplit(")",1)[0]

someParam = value1
anotherParam = (value2, value3)

>>>

Emile

Rhodri James

unread,
May 7, 2009, 8:19:21 PM5/7/09
to pytho...@python.org
On Fri, 08 May 2009 00:51:14 +0100, Rajanikanth Jammalamadaka
<rajan...@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

Rajanikanth Jammalamadaka

unread,
May 7, 2009, 9:25:39 PM5/7/09
to Rhodri James, pytho...@python.org
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

> --
> http://mail.python.org/mailman/listinfo/python-list
>

--
Rajanikanth

0 new messages