regular expression help

Skip Montanaro skip at pobox.com
Wed Feb 27 19:07:23 EST 2002


    Drew> I'm having some issues doing a small but irritating regular
    Drew> expression match.

As Jamie Zawinski said probably more than once on comp.lang.emacs (and
Fredrik Lundh has reminded us here):

    Some people, when confronted with a problem, think "I know, I'll use
    regular expressions".  Now they have two problems.

So, why use regular expressions?  If your data is formatted as simply as you
suggest, something like this would work:

lines = """
Location:Home
        555-1212
        555-3434
        555-5656

Location:Work
        555-9999
""".split("\n")

phones = {}
for line in lines:
    if line.startswith("Location:"):
        where = line.split(":")[1]
        phones[where] = []
    elif line.startswith("\t"):
        phones[where].append(line.strip())
print phones

I'm sure there are cleaner solutions, but this does seem to collect phone
numbers together according to their location.

-- 
Skip Montanaro (skip at pobox.com - http://www.mojam.com/)




More information about the Python-list mailing list