regexp in Python (from Perl)

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Mon Oct 20 11:23:37 EDT 2008


Pat a écrit :
> Bruno Desthuilliers wrote:
>> Pat a écrit :
>>> I have a regexp in Perl that converts the last digit of an ip address 
>>> to  '9'.  This is a very particular case so I don't want to go off on 
>>> a tangent of IP octets.
>>>
>>>  ( my $s = $str ) =~ s/((\d+\.){3})\d+/${1}9/ ;
>>>
>>> While I can do this in Python which accomplishes the same thing:
>>>
>>> ip = ip[ :-1 ]
>>> ip =+ '9'
>>
>> or:
>>
>> ip = ip[:-1]+"9"
> 
> Yes!  That's exactly what I was looking for.

Perhaps not - cf MRAB's post earlier in this thread and bearophile's answer.

While this was a straightforward one-liner version of your own code, it 
doesn't behave like the re version : this one only replace the last 
_character_, while the re version replaces the last _group_. If you want 
the re version's behaviour, use this instead:

ip = ".".join(ip.split('.')[0:3] + ['9'])


>>
>>
>>> I'm more interested, for my own edification in non-trivial cases, in 
>>> how one would convert the Perl RE to a Python RE that use groups.  I 
>>> am somewhat familiar using the group method from the re package but I 
>>> wanted to know if there was a one-line solution.
>>
>> Is that what you want ?
>>
>>  >>> re.sub(r'^(((\d+)\.){3})\d+$', "\g<1>9", "192.168.1.1")
>> '192.168.1.9'
>>
>>>>> re.sub(r'^(((\d+)\.){3})\d+$', "\g<1>9", "192.168.1.100")
>> '192.168.1.9'
>>
>>
> 
> Ah-hah!  That's how one uses groups. It's beautiful. I couldn't find 
> that in my books. 

Did you look at the FineManual(tm) ?-)

> 
> At first, I thought that using RE's in Python was going to be more 
> difficult than Perl.  A lot of my Perl code makes heavy use of RE 
> searching and substitution.

Well... Python's re module makes for a bit more verbose code, and I'm 
not sure all of the perl's regexps features are implemented. But that's 
still quite enough to shoot yourself in the foot IMHO !-)

Now while regexps are a must-have in a programmer's toolbox, you can 
already do quite a few things just using slicing and string methods. I 
highly recommend you read the relevant doc.

> I will never, ever write another line of Perl code as long as I live.

Hmmm... Never say "never again" ?-)



More information about the Python-list mailing list