Python's regular expression?

Mirco Wahab peace.is.our.profession at gmx.de
Mon May 8 08:31:02 EDT 2006


Hi Davy

> > More similar than Perl ;-)

But C has { }'s everywhere, so has Perl ;-)

> > And what's 'integrated' mean (must include some library)?

Yes. In Python, regular expressions are just
another function library - you use them like
in Java or C.

In Perl, it's part of the core language, you
use the awk-style (eg: /.../) regular expressions
everywhere you want.

If you used regexp in C/C++ before, you can use them
in almost the same way in Python - which may give you
an easy start.

BTW. Python has some fine extensions to the
perl(5)-Regexes, e.g. 'named backreferences'.

But you won't see much regular expressions
in Python code posted to this group, maybe
because it looks clunky - which is unpythonic ;-)

Lets see - a really simple find/match
would look like this in Python:

   import re

   t = 'blue socks and red shoes'
   p = re.compile('(blue|white|red)')
   if p.match(t):
      print t

which prints the text 't' because  of
the positive pattern match.

In Perl, you write:

   use Acme::Pythonic;

   $t = 'blue socks and red shoes'
   if ($t =~ /(blue|white|red)/):
     print $t

which is one line shorter (no need
to compile the regular expression
in advance).

> > I like C++ file I/O, is it 'low' or 'high'?

C++ has afaik actually three levels of I/O:

(1) - (from C, very low) operating system level, included
by <io.h> which provides direct access to operating system
services (read(), write(), lseek() etc.)

(2) - C-Standard-Library buffered IO, included by <stdio.h>,
provides structured 'mid-level' access like (block-) fread()/
fwrite(), line read (fgets()) and formatted I/O (fprintf()/
fscanf())

(3) - C++/streams library (high level, <fstream>, <iostream>, <sstream>),
which abstracts out the i/o devices, provides the same set of
functionality for any abstract input or output.

Perl provides all three levels of I/O, the 'abstracting' is introduced
by modules which tie 'handle variables' to anything that may receive
or send data.

Python also does a good job on all three levels, but provides
the (low level) operating system I/O by external modules (afaik).
I didn't do much I/O in Python, so I can't say much here.

Regards

Mirco



More information about the Python-list mailing list