r' question

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sun May 18 01:17:56 EDT 2008


En Sat, 17 May 2008 23:37:16 -0300, Dick Moores <rdm at rcblue.com> escribió:

> I have a text file of phone numbers, which I'd like to search with a regex.
>
> fstr = "\sjoe\s"
> regex = "^.*" + fstr + ".*$"
>
> fstr = "\sjoe\s"
> regex = "r'^.*" + fstr + ".*$'"

The r"..." is a signal to the parser - meaning "don't interpret the escape characters here". Note that the r is OUTSIDE the quotes. In your example, the escape characters are in fstr, so it should be written as r"\sjoe\s"

Now, if you want "the lines that contain the word joe surrounded by space", just use:

import re
regex = r"\sjoe\s"
p = re.compile(regex, re.I)
f = open('phone.txt', 'r')
for line in f:
     m = p.search(line)
     if m:
         print m.group()
f.close()

A file is its own line iterator (no need for readlines). And since you're iterating over lines, the regex doesn't have to test for it ^ and $.

-- 
Gabriel Genellina




More information about the Python-list mailing list