Regular Expressions...

Cameron Simpson cs at
Thu Jan 8 02:55:30 CET 2009

On 07Jan2009 19:51, Ken D'Ambrosio <ken at> wrote:
| Hi, all.  As a recovering Perl guy, I have to admit I don't quite "get"
| the re module.  For example, I'd like to do a few things (I'm going to use
| phone numbers, 'cause that's what I'm currently dealing with):
| 12345678900 -- How would I:
| - Get just the area code?
| - Get just the seven-digit number?
| In Perl, I'd so something like
| m/^1(...)(.......)/;
| and then I'd have the numbers in $1 and $2, respectively.  But the Python
| stuff simply isn't clicking for me.  If anyone could supply concrete
| examples of how to do the problem, above, that would be terrific.

I presume you're consulting this:

Something like this (untested):

  import re
  phone = '12345678900'
  num_re = re.compile('^1(...)(.......)')

num_re is now a regular expression object:
much as you get from a "precompiled" perl regular expression.

  m = num_re.match(phone)

m is now the result of a match against the phone number: is what was matched by the whole expression. is perl's
$1, is $2 etc.
For example:

  area_code =

There is also an expand() method that accepts \1, \2 etc in its
template. For direct substitutions (as in perl's s/this/that/) there is
the regular expression object sub() method.

It's a bit more broken out than you normally get in perl, but the pieces
are all there.

Cameron Simpson <cs at> DoD#743

Teamwork is essential. It lets you blame someone else.

More information about the Python-list mailing list