擅长:python、mysql、java
<p>有时,更简单的方法是不使用regex。只是个例子</p>
<pre><code>for line in open("dhcpd.conf"):
line = line.rstrip()
sline = line.split()
if "hardware ethernet" or "fixed-address" in line:
print sline[-1]
</code></pre>
<p>另一种方式</p>
<pre><code>data = open("file").read().split("}");
for item in data:
item = [ i.strip() for i in item.split("\n") if i != '' ];
for elem in item:
if "hardware ethernet" in elem:
print elem.split()[-1]
if item: print item[-1]
</code></pre>
<p>输出</p>
<pre><code>$ more file
host node20007
{
hardware ethernet 00:22:38:8f:1f:43;
fixed-address node20007.domain.com;
}
host node20008
{
hardware ethernet 00:22:38:8f:1f:44;
some-address node20008.domain.com;
}
$ python test.py
00:22:38:8f:1f:43;
fixed-address node20007.domain.com;
00:22:38:8f:1f:44;
some-address node20008.domain.com;
</code></pre>