2013-06-20 82 views
0

我試圖鍛鍊最好只打印帶數字的行。代碼只是部分完成,因爲我還是一般的新正則表達式,因此可能不會使用正確的方法或語法。單獨的re.matches做工精細,這是當我將它們組合起來,我得到不想要的結果:Python 3:匹配2個獨立條件的正則表達式

樣品字符串:

file = ''' 
title|Head1|Head2|Head3|head4 
----|------|-----|-----| 
1|1150976|0|25300992|bfa92720/bfa924f8|su|(None, None) 
2|1150976|0|25300992|bfa92720/bfa924f8|su|(None, None) 
3|1150976|0|25300992|bfa92720/bfa924f8|su|(None, None) 
4|1150976|0|25300992|bfa92720/bfa924f8|su|(None, None) 
5|1150976|0|25300992|bfa92720/bfa924f8|su|(None, None) 
All|processes:|MemAlloc|=|408125440|(None, None)|0.0.0.0 
|(None, None) 
0.0.0.0 ,text 
''' 
import re 
for line in file: 
    pat= re.match('(^[A-Z][a-z])|(^--.+)',line) # or use re.match('^[0-9]',line) and match pat != None 
    patIP = re.match ('^{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}',line)# 
    if patIP == None or pat == None: 
     print(line) 

我卡上的邏輯只打印出偶數行,我..可能完全關閉.. 請記住,我不想打印0.0.0.0(IP地址)行。

所需的輸出:

1|1150976|0|25300992|bfa92720/bfa924f8|su|(None, None) 
2|1150976|0|25300992|bfa92720/bfa924f8|su|(None, None) 
3|1150976|0|25300992|bfa92720/bfa924f8|su|(None, None) 
4|1150976|0|25300992|bfa92720/bfa924f8|su|(None, None) 
5|1150976|0|25300992|bfa92720/bfa924f8|su|(None, None) 

回答

1
import io 
import re 
import sys 

file = io.StringIO(''' 
title|Head1|Head2|Head3|head4 
----|------|-----|-----| 
1|1150976|0|25300992|bfa92720/bfa924f8|su|(None, None) 
2|1150976|0|25300992|bfa92720/bfa924f8|su|(None, None) 
3|1150976|0|25300992|bfa92720/bfa924f8|su|(None, None) 
4|1150976|0|25300992|bfa92720/bfa924f8|su|(None, None) 
5|1150976|0|25300992|bfa92720/bfa924f8|su|(None, None) 
All|processes:|MemAlloc|=|408125440|(None, None)|0.0.0.0 
|(None, None) 
0.0.0.0 ,text 
''') 

sys.stdout.writelines(line for line in file if re.match('\d+\|', line)) 
0

你可以試試這個:

import re 

file = ''' 
title|Head1|Head2|Head3|head4 
----|------|-----|-----| 
1|1150976|0|25300992|bfa92720/bfa924f8|su|(None, None) 
2|1150976|0|25300992|bfa92720/bfa924f8|su|(None, None) 
3|1150976|0|25300992|bfa92720/bfa924f8|su|(None, None) 
4|1150976|0|25300992|bfa92720/bfa924f8|su|(None, None) 
5|1150976|0|25300992|bfa92720/bfa924f8|su|(None, None) 
All|processes:|MemAlloc|=|408125440|(None, None)|10.93.103.73|(None, None) 
0.0.0.0 ,text 
''' 

matches = re.findall(r'^\d+\|.*$', file, re.MULTILINE) 
for match in matches: 
    print match 

當您使用多模式,^$代表 begining行結束的線