【问题标题】:Regular expression to match comma separated list of key=value where value can contain html?正则表达式匹配逗号分隔的 key=value 列表,其中 value 可以包含 html?
【发布时间】:2017-07-20 15:36:20
【问题描述】:

我正在尝试匹配一个逗号分隔的 key=value 列表,坦率地说,该值可以包含很多东西。

我使用的模式正是来自这个related question

split_up_pattern = re.compile(r'([^=]+)=([^=]+)(?:,|$)', re.X|re.M)

但是当值包含 html 时会导致问题。

这是一个示例脚本:

import re

text = '''package_contents=<p>The basic Super&nbsp;1050 machine includes the following:</p>
<p>&nbsp;</p>
<table style="" height: 567px;"" border=""1"">
<tbody>
<tr>
<td style=""width: 200px;"">
<ul>
<li>uper 1150 machine</li>
</ul>
</td>
<td>&nbsp;With dies fitted.
<ul>
<li>The Super 1050</li>
</ul>
</td>
</tr>
</tbody>
<table>,second_attribute=something else'''

split_up_pattern = re.compile(r'([\w_^=]+)=([^=]+)(?:,|$)', re.X|re.M)

matches = split_up_pattern.findall(text)

import ipdb; ipdb.set_trace()

print(matches)

输出:

ipdb> matches[0]
('package_contents', '<p>The basic Super&nbsp;1050 machine includes the following:</p>\n\n<p>&nbsp;</p>\n')
ipdb> matches[1]
('border', '""1"">\n\n<tbody>\n\n<tr>\n')
ipdb> matches[2]
('style', '""width: 200px;"">\n\n<ul>\n\n<li>uper 1150 machine</li>\n\n</ul>\n\n</td>\n\n<td>&nbsp;With dies fitted.\n\n<ul>\n\n<li>The Super 1050</li>\n\n</ul>\n\n</td>\n\n</tr>\n</tbody>\n<table>')
ipdb> matches[3]
('second_attribute', 'something else')

我想要的输出是:

matches[0]:

('package_contents', '<p>The basic Super&nbsp;1050 machine includes the following:</p><p>&nbsp;</p><table style="" height: 567px;"" border=""1""><tbody><tr><td style=""width: 200px;""><ul><li>uper 1150 machine</li></ul></td><td>&nbsp;With dies fitted.<ul><li>The Super 1050</li></ul></td></tr>
</tbody><table>',)

matches[1]:

('second_attribute', 'something else')

【问题讨论】:

  • 这是一个棘手的问题,您最初是如何获得这些数据的?您有什么方法可以在源头上对其进行标记?如果不能保证分隔符不会出现在值中,那么所有通过正则表达式(以及实际上大多数其他方法)进行解析的赌注都将被取消。您需要找到一个永远不会出现在值中的分隔符。
  • 您正在为多行正则表达式使用re.M 标志。我怀疑这是一个错误。
  • 如果逗号从未出现在 HTML 中的任何位置,则将搜索更改为 split_up_pattern = re.compile(r'([^=]+)=([^,]+)(?:,|$)') 应该可以。
  • @Phylogenesis 不幸的是,逗号确实出现了。
  • @ffledgling 我正在从电子商务网站导出。所以输出是csv 格式。然而,一列合并了所有additional_attributes,如上所示

标签: python regex


【解决方案1】:

您可以利用下一个键值对以以下内容开头的事实,而不是狭隘地基于分隔符(逗号或等号)进行解析:

,WORD=

这是一个想法的草图:

import re

text = '''...your example...'''

# Start of the string or our ,WORD= pattern.
rgx_spans = re.compile(r'(\A|,)\w+=')

# Get the start-end positions of all matches.
spans = [m.span() for m in rgx_spans.finditer(text)]

# Use those positions to break up the string into parsable chunks.
for i, s1 in enumerate(spans):
    try:
        s2 = spans[i + 1]
    except IndexError:
        s2 = (None, None)

    start = s1[0]
    end = s2[0]
    key, val = text[start:end].lstrip(',').split('=', 1)

    print()
    print(s1, s2)
    print((key, val))

【讨论】:

    猜你喜欢
    • 2013-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    • 2023-01-08
    • 1970-01-01
    相关资源
    最近更新 更多