Regular Expression

Fredrik Lundh fredrik at pythonware.com
Wed Dec 15 08:36:46 CET 2004


Michael McGarry wrote:

> I am horrible with Regular Expressions, can anyone recommend a book on it?
>
> Also I am trying to parse the following string to extract the number after load average.
>
> ".... load average: 0.04, 0.02, 0.01"
>
> how can I extract this number with RE or otherwise?

others have shown you that you don't really need RE:s in this case; just
split away until you have the right parts.

here's a RE solution:

    text = ".... load average: 0.04, 0.02, 0.01"
    print re.findall("\d[.\d]*", text)

"\d" matches a digit, "[.\d]" matches either a digit or a dot, and "*" says
that the immediately preceeding RE part can be repeated zero or more
times.  in other words, we're looking for a digit followed by zero or more
digits or dots.

to get floating point numbers, map the result through "float".

note that you can create pickier patterns (that ignores things like "1...."
and "1.1.1.1", for example) but that's overkill in this case.

</F> 






More information about the Python-list mailing list