我解析/etc/mtab
並且想要捕獲第二個字段和subvol
或subvolid
設置(如果有的話)在第四個字段中。但是,我在制定正確的正則表達式方面遇到了一些麻煩。請參閱:如何制定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
我在做什麼錯?如何制定一個正則表達式來實現我的目標?
謝謝。
你有沒有考慮過使用類似https://regex101.com/ #蟒蛇? – jonrsharpe