Help needed to retrieve text from a text-file using RegEx

Chris Rebert clp2 at rebertia.com
Mon Feb 9 18:40:57 CET 2009


On Mon, Feb 9, 2009 at 9:22 AM, Oltmans <rolf.oltmans at gmail.com> wrote:
> Here is the scenario:
>
> It's a command line program. I ask user for a input string. Based on
> that input string I retrieve text from a text file. My text file looks
> like following
>
> Text-file:
> -------------
> AbcManager=C:\source\code\Modules\Code-AbcManager\
> AbcTest=C:\source\code\Modules\Code-AbcTest\
> DecConnector=C:\source\code\Modules\Code-DecConnector\
> GHIManager=C:\source\code\Modules\Code-GHIManager\
> JKLConnector=C:\source\code\Modules\Code-JKLConnector
>
> -------------
>
> So now if I run the program and user enters
>
> DecConnector
>
> Then I'm supposed to show them this text "C:\source\code\Modules\Code-
> DecConnector" from the text-file. Right now I'm retrieving using the
> following code which seems quite ineffecient and inelegant at the same
> time
>
>  with open('MyTextFile.txt') as file:
>
>                for line in file:
>
>                    if mName in line: #mName is the string that
> contains user input
>
>                        Path =str(line).strip('\n')
>
>                        tempStr=Path
>
>                        Path=tempStr.replace(mName+'=',"",1)
>
> I was wondering if using RegEx will make this look better. If so, can
> you please suggest a Regular Expression for this? Any help is highly
> appreciated. Thank you.

If I might repeat Jamie Zawinski's immortal quote:
    Some people, when confronted with a problem, think "I know, I'll
use regular expressions." Now they have two problems.

If you add one section header (e.g. "[main]") to the top of the file,
you'll have a valid INI-format file which can be parsed by the
ConfigParser module --
http://docs.python.org/library/configparser.html

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list