我正在尝试将Ubuntu上的/etc/network/interfaces
文件格式分解为单个节(如手册页所述)。
这是我测试脚本的示例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+)?
和评论)以及所有节跟随它的文本,直到下一节开始。
我尝试过这样的代码,这听起来应该可行,但它会捕获一个字符串中的所有节:
re.split(r'^(iface|mapping|auto|allow-\w+|source(-\w)?|#.*)[.\n]+?',
open('/etc/network/interfaces').read(), flags=re.MULTILINE)
如何更正正则表达式以实现此目的?
Python版本是2.7
答案 0 :(得分:3)
你不需要正则表达式:
def userr = user.save flush:true
UserRole.create userr, roleUser.findByAuthority('ROLE_USER'), true
输出:
def stanza(fle):
with open(fle) as f:
vals = ("iface", "mapping", "auto", "allow-", "source")
tmp = []
for line in f:
if line.startswith(vals):
yield tmp
tmp = [line]
else:
tmp.append(line)
if tmp:
yield tmp
from pprint import pprint as pp
pp(list(stanza("foo.txt")))
如果要删除空白,请使用[['# The loopback network interface\n'],
['auto lo\n'],
['iface lo inet loopback\n', '\n'],
['auto eth0\n'],
['iface eth0 inet static\n',
' address 192.168.2.7\n',
' netmask 255.255.255.0\n',
' network 192.168.2.0\n',
' broadcast 192.168.2.255\n',
' gateway 192.0.2.254\n',
' dns-nameservers 12.34.56.78 12.34.56.79\n',
'\n'],
['auto eth0:0\n'],
['allow-hotplug eth0:0\n'],
['iface eth0:0 inet static\n',
' address 192.168.1.43\n',
' netmask 255.255.255.0\n',
'\n'],
['auto eth1\n'],
['iface eth1 inet dhcp\n', '\n'],
['auto eth2\n'],
['iface eth2 inet6 static\n',
' address 2001:db8::c0ca:1eaf\n',
' netmask 64\n',
' gateway 2001:db8::1ead:ed:beef\n',
'\n'],
['auto br0\n'],
['iface br0 inet static\n',
' address 10.10.0.15\n',
' netmask 255.255.255.0\n',
' gateway 10.10.0.1\n',
' bridge_ports eth0 eth1\n',
' up /usr/sbin/brctl stp br0 on']]
将其删除。