Reputation: 7800
I have the following list of string
mystring = [
'FOO_LG_06.ip',
'FOO_LV_06.ip',
'FOO_SP_06.ip',
'FOO_LN_06.id',
'FOO_LV_06.id',
'FOO_SP_06.id']
What I want to do is to print it out so that it gives this:
LG.ip
LV.ip
SP.ip
LN.id
LV.id
SP.id
How can I do that in python?
I'm stuck with this code:
for soth in mystring:
print soth
In Perl we can do something like this for regex capture:
my ($part1,$part2) = $soth =~ /FOO_(\w+)_06(\.\w{2})/;
print "$part1";
print "$part2\n";
Upvotes: 1
Views: 59
Reputation: 71598
If you want to do this in a manner similar to the one you know in perl, you can use re.search
:
import re
mystring = [
'FOO_LG_06.ip',
'FOO_LV_06.ip',
'FOO_SP_06.ip',
'FOO_LN_06.id',
'FOO_LV_06.id',
'FOO_SP_06.id']
for soth in mystring:
matches = re.search(r'FOO_(\w+)_06(\.\w{2})', soth)
print(matches.group(1) + matches.group(2))
matches.group(1)
contains the first capture, matches.group(2)
contains the second capture.
Upvotes: 2
Reputation: 493
different regex:
p='[^]+([A-Z]+)[^.]+(..*)'
>>> for soth in mystring:
... match=re.search(p,soth)
... print ''.join([match.group(1),match.group(2)])
Output:
LG.ip
LV.ip
SP.ip
LN.id
LV.id
SP.id
Upvotes: 0