Python正则表达式匹配分组

时间:2018-05-09 16:28:53

标签: python regex string python-2.7

RANDOMSTRING是字母数字,包括最多50个字符的空格

RANDOMSTRING $RANDOMFLOAT Paid with Visa ending in RANDOMINT *- For: RANDOMSTRING -*

RANDOMINTx *RANDOMSTRING* (RANDOMSTRING)
=E2=80=A2 RANDOMSTRING1

$RANDOMFLOAT
RANDOMINTx RANDOMSTRING (RANDOMSTRING)
=E2=80=A2 RANDOMSTRING2
=E2=80=A2 RANDOMSTRING3
=E2=80=A2 RANDOMSTRING4
=E2=80=A2 RANDOMSTRING5

$RANDOMFLOAT
RANDOMINTx *RANDOMSTRING* (RANDOMSTRING)
=E2=80=A2 RANDOMSTRING6
=E2=80=A2 RANDOMSTRING7

$RANDOMFLOAT
RANDOMINTx *RANDOMSTRING* (RANDOMSTRING)
=E2=80=A2 RANDOMSTRING8
=E2=80=A2 RANDOMSTRING9

您好我希望将每个RANDOMSTRING行中的=E2=80=A2作为数组数组。它们根据= E2 = 80 = A2分组进行分组。

预期输出示例:

[[RANDOMSTRING1], [RANDOMSTRING2, RANDOMSTRING3, RANDOMSTRING4, RANDOMSTRING5], [RANDOMSTRING6, RANDOMSTRING7], [RANDOMSTRING8, RANDOMSTRING9]]

我用的是什么:

menu_item_accessories_items = re.findall("((=E2=80=A2 .*$)|\n\n)", bodytext, re.MULTILINE)

输出我得到(操纵数组):

[(RANDOMSTRING1, RANDOMSTRING1), (RANDOMSTRING2, RANDOMSTRING2), (RANDOMSTRING3, RANDOMSTRING3), (RANDOMSTRING4, RANDOMSTRING4), (RANDOMSTRING5, RANDOMSTRING5), (RANDOMSTRING6, RANDOMSTRING6), (RANDOMSTRING7, RANDOMSTRING7), (RANDOMSTRING8, RANDOMSTRING8), (RANDOMSTRING9, RANDOMSTRING9)]

1 个答案:

答案 0 :(得分:0)

这可能不是最优雅的方法,而且我不确定如何处理此处未提供的角落情况,但下面的代码首先构建一个由空行分隔的单个列表。然后迭代所有条目,每次遇到分隔符时创建一个新列表。

lines = [x for x in bodytext.split('\n') if x == '' or x.startswith('=E2=80=A2')]

res = []
tmp = []
for line in lines:
    if line == '':
        if len(tmp) > 0:
            res += [tmp]
        tmp = []
    else:
        tmp += line.split(' ')[1:]

print res