On Thu, 6 Oct 2011 13:35:42 +0200, "roberto.prezi...@gmail.com" <roberto.prezi...@gmail.com> wrote: > Ciao, > mi sono bloccato con una regular expression su python. > Sto cercando di mettere i due punti ad un mac address e togliere quello > finale, ma non riesco a far funzionare questa regexp che su sed va così > bene: > > *da terminale:* > > echo "00A1B2AABBCC" | sed 's/\(..\)/\1:/g;s/:$//' > > *con python :* > >>>> mac = "00A0BCAABBCC" >>>> mac.replace("\(..\)","\1:") > '00A0BCAABBCC' >>>> mac.replace("..","\1:") > '00A0BCAABBCC' >>>> mac.replace("..",":") > '00A0BCAABBCC' >>>> mac.replace("\.\.",":") > '00A0BCAABBCC' > > dove sbaglio ?
Nell'assumere che string.replace capisca le espressioni regolari :) >>> import re >>> re.sub(r"(..(?!$))", r"\1:", "00A1B2AABBCC") '00:A1:B2:AA:BB:CC' La parolaccia (?!$) è un negative look-ahead, serve a non far matchare l'ultima coppia di caratteri. Se vuoi una regexp che non dica parolacce puoi usare >>> re.sub(r"(..)", r"\1:", "00A1B2AABBCC")[:-1] -- Daniele Varrazzo - Develer S.r.l. http://www.develer.com _______________________________________________ Python mailing list Python@lists.python.it http://lists.python.it/mailman/listinfo/python