按行分组匹配
创始人
2024-08-22 02:30:15
0

下面是一个示例代码,演示如何按行分组匹配:

import re

def group_matching_lines(pattern, text):
    groups = []
    lines = text.split("\n")
    current_group = []
    for line in lines:
        match = re.search(pattern, line)
        if match:
            current_group.append(line)
        elif current_group:
            groups.append(current_group)
            current_group = []
    if current_group:
        groups.append(current_group)
    return groups

# 示例用法
text = """
Line 1: This is a test
Line 2: Match this line
Line 3: This line doesn't match
Line 4: Match this line too
Line 5: This line doesn't match either
"""

pattern = r"Match"

matching_groups = group_matching_lines(pattern, text)

for group in matching_groups:
    print("Matching group:")
    for line in group:
        print(line)
    print()

输出结果:

Matching group:
Line 2: Match this line

Matching group:
Line 4: Match this line too

在这个示例中,group_matching_lines函数接受一个正则表达式模式和一段文本作为输入。它将文本按行分割,并逐行匹配模式。如果某一行匹配成功,就将该行添加到当前分组中。如果某一行不匹配并且当前分组不为空,则将当前分组添加到结果列表中,并创建一个新的空的当前分组。最后,如果当前分组不为空,则将其添加到结果列表中。

在示例中,我们使用r"Match"作为模式,它匹配任何包含“Match”的行。输出结果中只包含匹配的行,并按组进行分组。每个匹配组都打印在一行上,之间用空行分隔。

相关内容

热门资讯

黑科技辅助!wepoke一定有... 黑科技辅助!wepoke一定有挂,(WePoKe好友)原来真的有挂,切实教程(有挂解惑)-哔哩哔哩;...
黑科技辅助!wepower辅助... 黑科技辅助!wepower辅助器,(WePoKe美元局)原来真的有挂,AA德州教程(有挂详细)-哔哩...
黑科技辅助!wepower辅助... 黑科技辅助!wepower辅助器,(WePoKe方法)原来真的有挂,高科技教程(存在有挂)-哔哩哔哩...
黑科技辅助!悟空黑桃a辅助,(... 黑科技辅助!悟空黑桃a辅助,(悟空黑桃a辅助软件)原来真的有挂,详细教程(详细教程)-哔哩哔哩;黑科...
黑科技辅助!wepokeai代... 黑科技辅助!wepokeai代打逻辑,(WePoKe诀窍)原来真的有挂,详细教程(有挂教程)-哔哩哔...
黑科技辅助!aapoker辅助... 黑科技辅助!aapoker辅助,(AAPoKer黑科技)原来真的有挂,解密教程(竟然)-哔哩哔哩;是...
黑科技辅助!wepoke计算辅... 黑科技辅助!wepoke计算辅助,(WePoKeai机器人)原来真的有挂,技巧教程(证实有挂)-哔哩...
黑科技辅助!德扑ai智能工具,... 黑科技辅助!德扑ai智能工具,(德扑ai俱乐部)原来真的有挂,2025新版总结(助手)-哔哩哔哩,德...
黑科技辅助!悟空黑桃a免费赛,... 黑科技辅助!悟空黑桃a免费赛,(悟空德州app)原来真的有挂,实用技巧(神器)-哔哩哔哩;悟空黑桃a...
黑科技辅助!AApoker靠谱... 黑科技辅助!AApoker靠谱,(AAPoKer存在)原来真的有挂,曝光教程(方法)-哔哩哔哩;1、...