Python正则表达式来查找html标记内容中的所有百分比

2024-03-29 09:01:09 发布

您现在位置:Python中文网/ 问答频道 /正文

有两个条件我正试图满足一个正则表达式正在刮html上使用。所有示例代码都是字符串:

  1. 例如字符串=<p>40% flights: Private bookings 20-15% bonus: Private airfairs 10% Excellence: Public Vacation 5-0% persons: Public Sightseeing</p>

我使用的re.findall(r'\d+%', ex_string)产生: ['40%'、'15%'、'10%'、'0%']

但是在20-15%的情况下,我需要在输出中得到20-15%,而不是仅仅15%

  1. <table border="0" style="border-collapse: collapse; width: 100%;"> <tbody> <tr> <td style="width: 50%;">85%</td>

在这里使用re.findall(r'\d+%', ex_string)可以得到['100%,'85%],但是我只想要'width'不在前面的百分比

第二个例子的期望结果是['85%']

需要做哪些修改才能同时满足这两个要求


Tags: 字符串restringstylehtmlprivatepublic条件
1条回答
网友
1楼 · 发布于 2024-03-29 09:01:09

使用HTML解析器将使这更简单。如果你想要一个正则表达式的解决方案,消极的向后看可能是一种方法

import re

ex_string = """
<p>40% flights: Private bookings 20-15% bonus: Private airfairs 10% Excellence: Public Vacation 5-0% persons: Public Sightseeing</p>
<table border="0" style="border-collapse: collapse; width: 100%;">
<tbody>
<tr>
<td style="width: 50%;">85%</td>
"""

g = re.findall(r'(?<!width: )(?<!\d)(\d+%|\d+\-\d+%)', ex_string)
print(g)

也就是说width:\d不应该在(\d+%|\d+\-\d+%)之前

输出:

['40%', '20-15%', '10%', '5-0%', '85%']

相关问题 更多 >