Python re expr from Perl to Python

Thomas Ploch Thomas.Ploch at gmx.net
Sun Jan 7 15:01:29 EST 2007


Florian Diesch schrieb:
> "Michael M." <michael at mustun.ch> wrote:
> 
>> In Perl, it was:
>>
>>
>>   ## Example: "Abc | def | ghi | jkl"
>>   ##       -> "Abc ghi jkl"
>>   ## Take only the text betewwn the 2nd pipe (=cut the text in the 1st
>> pipe).
>>   $na =~ s/\ \|(.*?)\ \|(.*?)\ \|/$2/g;
>>
>>   ## -- remove [ and ] in text
>>   $na =~ s/\[//g;
>>   $na =~ s/\]//g;
>>   # print "DEB: \"$na\"\n";
>>
>>
>> # input string
>> na="Abc | def | ghi | jkl [gugu]"
>> # output
>> na="Abc ghi jkl gugu"
>>
>>
>> How is it done in Python?
> 
>>>> import re
>>>> na="Abc | def | ghi | jkl [gugu]"
>>>> m=re.match(r'(\w+ )\| (\w+ )\| (\w+ )\| (\w+ )\[(\w+)\]', na)
>>>> na=m.expand(r'\1\2\3\5')
>>>> na
> 'Abc def ghi gugu'

I'd rather have the groups grouped without the whitespaces

 >>> import re
 >>> na="Abc | def | ghi | jkl [gugu]"
 >>> m=re.match(r'(\w+) \| (\w+) \| (\w+) \| (\w+) \[(\w+)\]', na)
 >>> na=m.expand(r'\1 \3 \4 \5')
 >>> na
 'Abc ghi jkl gugu'

Thomas




More information about the Python-list mailing list