2015-10-05 28 views
1

我解析/etc/mtab並且想要捕獲第二個字段和subvolsubvolid設置(如果有的話)在第四個字段中。但是,我在制定正確的正則表達式方面遇到了一些麻煩。請參閱:如何制定Python正則表達式來獲取btrfs subvol ID

import re 
def test(regex): 
    def helper(string): 
     m = re.match(regex, string) 
     if m is None: print("no matches") 
     else: print(m.groups()) 
    helper("/dev/sdb2 /mnt/btrfs btrfs rw,noatime 0 0") 
    helper("/dev/sdb2 /tmp btrfs rw,noatime,subvol=os-aux/kubuntu-lts/tmp 0 0") 
    helper("/dev/sdb2 /tmp btrfs noatime,subvol=os-aux/kubuntu-lts/tmp,rw 0 0") 
    helper("/dev/sdb2 /tmp btrfs subvol=os-aux/kubuntu-lts/tmp,rw,noatime 0 0") 

預期輸出當然是:

('/mnt/btrfs', None) 
('/tmp', 'subvol=os-aux/kubuntu-lts/tmp') 
('/tmp', 'subvol=os-aux/kubuntu-lts/tmp') 
('/tmp', 'subvol=os-aux/kubuntu-lts/tmp') 

現在我的實驗,其結果顯示:

>>> test("\S+ (\S+) \S+ \S+(subvol(?:id)?=[^ ,]+)?") 
('/mnt/btrfs', None) 
('/tmp', None) 
('/tmp', None) 
('/tmp', None) 
>>> test("\S+ (\S+) \S+ \S+?(subvol(?:id)?=[^ ,]+)?") 
('/mnt/btrfs', None) 
('/tmp', None) 
('/tmp', None) 
('/tmp', None) 
>>> test("\S+ (\S+) \S+ \S+(subvol(?:id)?=[^ ,]+)") 
no matches 
('/tmp', 'subvol=os-aux/kubuntu-lts/tmp') 
('/tmp', 'subvol=os-aux/kubuntu-lts/tmp') 
no matches 

我在做什麼錯?如何制定一個正則表達式來實現我的目標?

謝謝。

+1

你有沒有考慮過使用類似https://regex101.com/ #蟒蛇? – jonrsharpe

回答

2

這個工作對我來說

\S+ (\S+) \S+ \S*(subvol(?:id)?=[^ ,]*) 

還,這是一個正則表達式超好用網站 https://www.debuggex.com/

編輯:

沒有subvol這其中也對那些符合條件:

\S+ (\S+) \S+ (?:\S*(subvol(?:id)?=[^ ,]*)|\S*) 
+0

對不起,但沒有正確測試第一個採樣線,即沒有'subvol' ... – jamadagni

+0

檢查該案例的編輯 –