重复regex组任意麻木

2024-04-26 06:22:20 发布

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

我有这个示例文本片段

headline:
        Status[apphmi]: blubb, 'Statustext1'
        Main[apphmi]: bla, 'Maintext1'Main[apphmi]: blaa, 'Maintext2'
        Popup[apphmi]: blaaa, 'Popuptext1'

我想提取“”中的单词,但按上下文排序(status、main、popup)。你知道吗

我当前的正则表达式是(example at pythex.org):

headline:(?:\n +Status\[apphmi\]:.* '(.*)')*(?:\n +Main\[apphmi\]:.* '(.*)')*(?:\n +Popup\[apphmi\]:.* '(.*)')*

但这样我只能得到“Maintext2”,而不是两者都有。我不知道如何把这些组重复到任意的数字。你知道吗


Tags: 文本示例mainstatuspopupblaheadlineblaa
1条回答
网友
1楼 · 发布于 2024-04-26 06:22:20

你可以试试这个:

r"(.*?]):(?:[^']*)'([^']*)'"g

Look here 每个匹配的Group1和group2都包含键值对

你不能用正则表达式把第二个匹配合并为一个,一旦你得到所有的对。。。您可以在这里应用一些编程来将重复的键合并为一个键。你知道吗

这里我使用了dictionary of list,如果dictionary中已经存在一个键,那么应该将该值附加到列表中,否则插入一个新的键和一个具有该值的新列表。你知道吗

This is how it should be done (tested in python 3+)

import re

d = dict()
regex = r"(.*?]):(?:[^']*)'([^']*)'"

test_str = ("headline:        \n"
    "Status[apphmi]: blubb, 'Statustext1'\n"
    "Main[apphmi]: bla, 'Maintext1'Main[apphmi]: blaa, 'Maintext2'\n"
    "Popup[apphmi]: blaaa, 'Popuptext1'")

matches = re.finditer(regex, test_str)

for matchNum, match in enumerate(matches):
    if match.group(1) in d:
        d[match.group(1)].append(match.group(2))
    else:
        d[match.group(1)] = [match.group(2),]
print(d)

输出:

{
'Popup[apphmi]': ['Popuptext1'], 
'Main[apphmi]': ['Maintext1', 'Maintext2'], 
'Status[apphmi]': ['Statustext1']
}

相关问题 更多 >

    热门问题