我正在尝试解析/etc/mtab
但排除/boot
。我想也许非捕获组可能是要走的路,但它不能像我预期的那样工作。这是我构造的正则表达式:
proc = subprocess.Popen(["ssh", server, "cat", mtab],stdout = subprocess.PIPE)
for line in proc.stdout:
fsMatch = re.search(r'([\w/:]+) (/([\w/:-]+)|(?:boot)) (nfs|ext3)', line)
if fsMatch:
print fsMatch.group(1,2,4)
输出:
('/dev/sda1', '/boot', 'ext3')
('/dev/mapper/foo1', '/export/foo1', 'ext3')
('/dev/mapper/foo2', '/export/foo2', 'ext3')
('/dev/mapper/foo3', '/export/foo3', 'ext3')
('/dev/mapper/foo4', '/export/foo4', 'ext3')
('/dev/mapper/foo5', '/export/foo5', 'ext3')
('servernfs:/install', '/mnt', 'nfs')
我非常确信|
是错误的(显然更多是错误的)但是已经遇到了障碍。
我正在查找/[\w/:-]+
的所有匹配项,但将匹配项排除在/boot
建议?
答案 0 :(得分:2)
你需要使用负面的lookbehind或负向前瞻,用下面的提示描述here:
r'^(?!/boot).*$'
如果你需要捕获'servernfs:'一个而不是'servernfs:/ boot',你需要撒上一点'|'和'([a-z] + :)'位于顶部('^'之后)
答案 1 :(得分:1)
只需排除该行:
for line in proc.stdout:
if 'boot' not in line:
# the rest
但是,由于mtab
在空格上分隔,因此您可以使用split
:
>>> with open('foo.txt') as f:
... lines = [line.split(' ') for line in f if 'boot' not in line]
...