need help extracting data from a text file

Tom Anderson twic at urchin.earth.li
Wed Nov 9 12:56:15 EST 2005


On Mon, 7 Nov 2005, Kent Johnson wrote:

> nephish at xit.net wrote:
>
>> i have a text file with a bunch of values scattered throughout it. i am 
>> needing to pull out a value that is in parenthesis right after a 
>> certain word, like the first time the word 'foo' is found, retrieve the 
>> values in the next set of parenthesis (bar) and it would return 'bar'
>
> It's pretty easy with an re:
>
>>>> import re
>>>> fooRe = re.compile(r'foo.*?\((.*?)\)')

Just out of interest, i've never really got into using non-greedy 
quantifiers (i use them from time to time, but hardly ever feel the need 
for them), so my instinct would have been to write this as:

>>> fooRe = re.compile(r"foo[^(]*\(([^)]*)\)")

Is there any reason to use one over the other?

>>>> fooRe.search('foo(bar)').group(1)
> 'bar'
>>>> fooRe.search('This is a foo bar baz blah blah (bar)').group(1)
> 'bar'

Ditto.

tom

-- 
[of Muholland Drive] Cancer is pretty ingenious too, but its best to
avoid. -- Tex



More information about the Python-list mailing list