如何构造Python正则表达式来获取btrfs子卷ID

2024-06-09 04:03:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在分析/etc/mtab,希望捕获第二个字段和第四个字段中的subvolsubvolid设置(如果有的话)。但是,我在制定正确的正则表达式时遇到了一些困难。请看:

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

我做错什么了?如何制定正则表达式来实现我的目标?你知道吗

谢谢。你知道吗


Tags: devtesthelpernoneostmprwaux
1条回答
网友
1楼 · 发布于 2024-06-09 04:03:57

这个适合我

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

此外,这是一个超级有用的网站正则表达式 https://www.debuggex.com/

编辑:

这个也适用于没有子卷的:

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

相关问题 更多 >