在Python中通过正则表达式提取字符串的一部分

时间:2014-03-17 06:11:32

标签: python regex

我有以下字符串列表

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']

我想要做的就是打印出来,以便它能够:

LG.ip 
LV.ip 
SP.ip 
LN.id
LV.id 
SP.id

我怎么能在python中做到这一点?

我坚持使用这段代码:

   for soth in mystring:
       print soth

在Perl中,我们可以为正则表达式捕获做类似的事情:

my ($part1,$part2) = $soth =~ /FOO_(\w+)_06(\.\w{2})/;
print "$part1";
print "$part2\n";

2 个答案:

答案 0 :(得分:2)

如果您想以类似于perl中所知的方式执行此操作,则可以使用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)包含第一个捕获,matches.group(2)包含第二个捕获。

ideone demo

答案 1 :(得分:0)

不同的正则表达式:

  
    
      

P =' [^ ] + ([A-Z] +)[^。] +(。*)'

    
  
    >>> for soth in mystring:
    ...    match=re.search(p,soth)
    ...    print ''.join([match.group(1),match.group(2)])

输出:

LG.ip

LV.ip

SP.ip

LN.id

LV.id

SP.id