pdubois
pdubois

Reputation: 7800

Extracting part of string through regex in Python

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

Answers (2)

Jerry
Jerry

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.

ideone demo.

Upvotes: 2

sanooj
sanooj

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

Related Questions