2017-04-22 75 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 
相關問題