【发布时间】:2015-12-20 11:42:33
【问题描述】:
我正在尝试将 Ubuntu 上的 /etc/network/interfaces 文件格式分解为单个节(如手册页所称)。
这是我测试脚本的示例接口文件:
# The loopback network interface
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet static
address 192.168.2.7
netmask 255.255.255.0
network 192.168.2.0
broadcast 192.168.2.255
gateway 192.0.2.254
dns-nameservers 12.34.56.78 12.34.56.79
auto eth0:0
allow-hotplug eth0:0
iface eth0:0 inet static
address 192.168.1.43
netmask 255.255.255.0
auto eth1
iface eth1 inet dhcp
auto eth2
iface eth2 inet6 static
address 2001:db8::c0ca:1eaf
netmask 64
gateway 2001:db8::1ead:ed:beef
auto br0
iface br0 inet static
address 10.10.0.15
netmask 255.255.255.0
gateway 10.10.0.1
bridge_ports eth0 eth1
up /usr/sbin/brctl stp br0 on
我需要的是一个包含每个节的字符串数组(iface、mapping、auto、allow-\w+、source(-\w+)? 和 cmets)以及它后面的所有文本,直到下一个开始节。
我尝试过这样的代码,听起来应该可以,但是它将所有节捕获在一个字符串中:
re.split(r'^(iface|mapping|auto|allow-\w+|source(-\w)?|#.*)[.\n]+?',
open('/etc/network/interfaces').read(), flags=re.MULTILINE)
如何更正正则表达式以实现此目的?
Python 版本是 2.7
【问题讨论】:
-
澄清一下,每个节都是由空行分隔的信息块之一?
-
@timgeb 没有每个节是从一个关键字的开头到下一个关键字的开头,包括它们之间的所有行(例如
static方法中的选项iface节像address和netmask都应该是iface节的一部分,因此在同一个字符串中)。 -
对不起,我还是不明白节的定义。您可能应该使用示例文件的预期结果信息更新您的帖子。