Python 正则表达式将组分组为单个字符串?

Python regex grouping groups into single string?

我正在尝试对一些我只对某些模式之间的文本感兴趣的文本进行正则表达式搜索。

示例文本:

<h2><font color='#fff'>some text </font></h2><HR noshade size="5" width="50%" align="center"><table><tr><th id='t1'>Host  </th><th>10.0.1.1</th></tr><th id='t1'>Port  </th><th>8080</th></tr><th id='t1'>User  </th><th>chris</th></tr><th id='t1'>Password  </th><th>chris</th></tr></table><h4><font color='#fff'>
...
<h2><font color='#fff'>some more text </font></h2><HR noshade size="5" width="50%" align="center"><table><tr><th id='t1'>Host  </th><th>10.0.1.2</th></tr><th id='t1'>Port  </th><th>9090</th></tr><th id='t1'>User  </th><th>bob</th></tr><th id='t1'>Password  </th><th>bob</th></tr></table><h4><font color='#fff'>

这是我的正则表达式:

Host.*?<th>(.*?)<.*Port.*?<th>(.*?)<.*User.*?<th>(.*?)<.*Password.*?<th>(.*?)<

每个正则表达式匹配都返回一个列表,这不是我想要的。我希望将这些组组合成一个字符串。

这是我想要的输出:

10.0.1.1 8080 chris chris
10.0.1.2 9090 bob bob

这是我正在做的事情:

lines = []
lines.extend(re.findall(r"Host.*?<th>(.*?)<.*Port.*?<th>(.*?)<.*User.*?<th>(.*?)<.*Password.*?<th>(.*?)<", s))
print (lines)

这给了我:

[('10.0.1.1', '8080', 'chris', 'chris'), ('10.0.1.2', '9090', 'bob', 'bob')]

任何人都可以解释为什么会发生这种情况以及我如何才能得到我想要的东西吗?

谢谢, 克里斯

re.findall returns 包含 two or more parentheses 时每个匹配组的元组列表。您可以进一步处理它以匹配您想要的内容:

strings = [' '.join(tup) for tup in output]