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.
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. Thank you very, very much!
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.
I will never, ever write another line of Perl code as long as I live.
--
http://mail.python.org/mailman/listinfo/python-list