【问题标题】:Python regex grouping groups into single string?Python正则表达式将组分组为单个字符串?
【发布时间】:2021-06-17 20:08:43
【问题描述】:

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

示例文本:

<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')]

谁能解释为什么会发生这种情况以及我如何才能得到我想要的?

谢谢, 克里斯

【问题讨论】:

  • 你会得到一个元组列表,因为findall 返回一个匹配列表,在这种情况下是元组。您是否尝试过使用join 来连接每个元组的元素?
  • print('\n'.join([' '.join(values) for values in lines]))
  • 谢谢贾斯汀

标签: python string list python-re


【解决方案1】:

当您包含two or more parentheses 时,re.findall 返回每个匹配组的元组列表。您可以进一步处理以匹配您想要的:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-23
    • 1970-01-01
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多