<p><strong>更新</strong>我刚刚注意到您在代码中获得结果的真正原因:</p>
<pre><code>for host in f:
match = re_hostinfo.search(host)
if match:
print match.groups()
</code></pre>
<p><code>host</code><em>引用一行,但是您的模式需要在两行上工作。</em></p>
<p>试试这个:</p>
<pre><code>data = f.read()
for x in regex.finditer(data):
process(x.groups())
</code></pre>
<p>其中<code>regex</code>是匹配两行以上的编译模式。</p>
<p>如果您的文件很大,并且您确定感兴趣的部分总是分布在两行上,那么您可以一次读取一行文件,检查该行是否为模式的第一部分,设置一个标志来告诉您是否应为第二部分检查下一行。如果您不确定,它会变得复杂,可能足以开始查看<a href="http://pyparsing.wikispaces.com/" rel="noreferrer">pyparsing</a>模块。</p>
<p>现在回到最初的答案,讨论您应该使用的模式:</p>
<p>不需要多行;只需匹配空白即可。使用以下构建基块构建模式:</p>
<p>(1)固定文本
(2) 一个或多个空白字符
(3) 一个或多个非空白字符</p>
<p>然后用括号括起来。</p>
<p>试试这个:</p>
<pre><code>>>> m = re.search(r'(hardware ethernet\s+(\S+));\s+\S+\s+(\S+);', data)
>>> print m.groups()
('hardware ethernet 00:22:38:8f:1f:43', '00:22:38:8f:1f:43', 'node20007.domain.com')
>>>
</code></pre>
<p>请考虑使用“详细模式”。。。你可以用它来记录
模式匹配哪些数据片段,它通常可以帮助在第一时间正确地获得模式。示例:</p>
<pre><code>>>> regex = re.compile(r"""
... (hardware[ ]ethernet \s+
... (\S+) # MAC
... ) ;
... \s+ # includes newline
... \S+ # variable(??) text e.g. "fixed-address"
... \s+
... (\S+) # e.g. "node20007.domain.com"
... ;
... """, re.VERBOSE)
>>> print regex.search(data).groups()
('hardware ethernet 00:22:38:8f:1f:43', '00:22:38:8f:1f:43', 'node20007.domain.com')
>>>
</code></pre>