[Tutor] advice on idiomatic python and re module question

Paul Worrall paul at basilisk.ukfsn.org
Mon May 17 16:01:02 EDT 2004


On Monday 17 May 2004 19:34, Andrew Fant wrote:
> Afternoon all,
>    After intending to get serious about learning python for a couple years
> now, I have finally bit the bullet and started to use python for odd jobs
> around the office.  I have run into a couple issues that I could use some
> help with, though.
>
> First, I cannot seem to compile and use more than one regexp in a program:
>
> if I use:
>
> pattern1=re.compile('^#')
> pattern2=re.compile('eth0')
>
> to define the patterns, I can use:
>
> if pattern1.match(line):
>
> to check for a comment line succesfully,but
>
> if pattern2.match(line):
>
> always fails, even when a file containing that string is read in.  Grep has
> no trouble finding the string, and I have single stepped through the code
> with a debugger and I see the line fail to match.   Doe anyone have any
> suggestions on what I am doing wrong?
>

Have you realised that the match method of a regular expression object returns 
a match object only if the regular expression matches at the beginning of the 
string?  i.e. patern2.match(line) would match:

eth0 is the first ethernet port

but not:

IP Address 192.168.2.10 is bound to eth0

If you want to match anywhere in the line, use pattern2.search(line)

-- 
Paul



More information about the Tutor mailing list