google at mrabarnett.plus.com
Thu Jan 8 00:51:09 CET 2009
Ken D'Ambrosio 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
> 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
> that stuff 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.
Perl puts the captured text into variables as a side-effect, which, from
the Python point of view, is undesirable 'magic'. The Python way is for
the result to be returned like any normal function or method call:
match = re.search(r"^1(...)(.......)", phone_number)
# match is now a match object if successful or None if unsuccessful
area_code = match.group(1)
local_code = match.group(2)
# area_code, local_code = match.groups()
No magic involved!
(In this case simple string slicing would be simpler and faster.)
More information about the Python-list