2017-04-22 74 views
2

我有一个文件abcd.txt包含:如何选择两个特殊字符之间的数据?蟒蛇

"""  
hello,123 [1231,12312]1231231  
hello, world[3r45t,3242]6542  
123 213 135  
4234 gdfg gfd 32 
sd23 234 sdf 23  
hi, hello[234,23423]561  
hello, hi[123,123]985 
""" 

我要打印的是字符串第二“”字符,直到‘]’之后。 我的输出应该是:

12312 
3242 
23423 
123 

我尝试这样做:

def select(self): 
     file = open('gis.dat') 
     list1 = [] 
     for line in file: 
      line = line.strip() 
      if re.search('[a-zA-Z]',line): 
       list1.append(line.partition(',')[-1].rpartition(']')[0]) 
     return list1 
+0

'3242'不会在2个逗号之后出现。 –

+0

对不起,我在那里犯了一个错误。我改变了它 –

回答

1

您可以使用:

import re 
for line in open("abcd.txt"): 
    match = re.findall(r".*?,.*?,(\d+)", line) 
    if match: 
     print match[0] 

输出:

12312 
3242 
23423 
123 
相关问题