[Tutor] Regex

Alan Gauld alan.gauld at freenet.co.uk
Tue Aug 15 00:32:33 CEST 2006


> so I thought I'd write something like this:
> 
> filename = '/home/acl_home/PhD/CurrentPhD/extensions1_14.8.6.tex'
> 
> infile = open(filename,'r')
> 
> def_start = "\\begin\{defn\}"
> def_end = "\end{defn}"
> 
> def_start_reg = re.compile(def_start)
> 
> l = 0
> while l < 500:
>     line = infile.readline()
>     #print l, line
>     res = re.search(def_start_reg,line)
>     print l, res
>     l = l+1

Use a for loop instead of the while loop.
And use the methods of the compiled regex object:

for n,line in enumerate(open(filename)):
    res = def_start_reg.search(line)
    print n,res

Does that work?

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list