【问题标题】:regex for string in pythonpython中字符串的正则表达式
【发布时间】:2016-01-10 18:33:51
【问题描述】:

我有以下字符串,我想提取字段的值

<td class="label" width="150"">State</td><td width="" class="field">Approved&nbsp;</td>

在这种情况下它应该被批准

有时输入也可以是这样的

<td class="label" width="150"">Type</td><td width="" class="field">Technical&nbsp;Document&nbsp;</td>

其中 shd 导致技术文档

有时候可以

 <td class="label" width="150"">Title</td><td width="" class="field">Reversal Plate</td>

在这种情况下,它将是反转板

我们如何为这样的字符串编写正则表达式。

【问题讨论】:

  • 您看起来正在尝试使用正则表达式解析 HTML。您想要更好的选择吗?

标签: python regex python-2.7 python-3.x


【解决方案1】:

不要为此使用正则表达式,您应该使用一些 HTML/XML 解析器,例如 BeautifulSoup

from bs4 import BeautifulSoup
soup = BeautifulSoup(s,'html.parser') #`s` being your string.
for td in soup.findAll('td',class_="field"):
    print(td.get_text())

以上对于您的两个示例都将得到正确的结果。

演示 -

>>> s = """<td class="label" width="150"">State</td><td width="" class="field">Approved&nbsp;</td>"""
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(s,'html.parser')
>>> for td in soup.findAll('td',class_="field"):
...     print(td.get_text())
...
Approved 
>>> s = """<td class="label" width="150"">Type</td><td width="" class="field">Technical&nbsp;Document&nbsp;</td>"""
>>> soup = BeautifulSoup(s,'html.parser')
>>> for td in soup.findAll('td',class_="field"):
...     print(td.get_text())
...
Technical Document 

【讨论】:

  • 我想试试可用的选项,是否可以使用正则表达式获得它?
  • @RidhiJain 您可以查看其他答案,但请注意它仅适用于非常特定的情况。因此,如果您 100% 确定您给出的三个示例是您想要找到的唯一案例,您可以使用它。如果标签中"&gt; 之间有一个小范围,它将停止工作。但是您将获得的大多数正则表达式解决方案都是这样的。
  • 如何安装漂亮的 Soup....我是 python 新手,如何检查我正在运行的 wat 版本
  • import sys; print(sys.version) 应该为您提供当前的 python 版本。您可以使用pip install beautifulsoup 安装来自pip 的漂亮汤。
  • stackoverflow.com/questions/19957194/… 这可能对你有帮助。
【解决方案2】:

正如@Anand S Kumar 所说,您不必使用regex,使用Beautifulsoup 更快。但是,由于您要求regex 解决方案,您可以使用以下代码:

import re
s = '<td class="label" width="150"">State</td><td width="" class="field">Approved&nbsp;</td>'
m = re.compile('"field">(.*)<')
print (m.search(s).group(1))

输出:

Approved&nbsp;

regex 解决方案将匹配class="field"&gt;....&lt;/td&gt; 中的任何内容

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-28
    • 1970-01-01
    • 1970-01-01
    • 2012-02-17
    • 2020-11-29
    • 2020-05-05
    • 2011-11-28
    • 2021-09-07
    相关资源
    最近更新 更多