首页 > 解决方案 > 在两个字符串之间拆分正则表达式 python,但包含使用 re.split 并返回一个列表

问题描述

我正在尝试将一段文本拆分为如下格式的文件:

module 
some text
endmodule

module 
some other text
endmodule

在单词 module 和 endmodule 之间,并且仍然在输出字符串中包含 module 和 endmodule。

这不是其他正则表达式问题的重复,因为我正在尝试使用 re.split() 返回列表,而不是查找。

这是我尝试过的正则表达式

s=file.read()
l=re.split("module(.*)endmodule",s)

但它不会分裂任何东西......

理想情况下,最终输出将是一个包含两个模块作为字符串的列表,

['module\n sometext\n endmodule', 'module\n someothertext\n endmodule']

标签: pythonregex

解决方案


我的猜测是您可能想要设计一个类似于以下内容的表达式:

module(.*?)endmodule

不过不确定。

用 re.finditer 测试

import re

regex = r"module(.*?)endmodule"

test_str = ("module \n"
    "some text\n"
    "endmodule\n\n"
    "module \n"
    "some other text\n"
    "endmodule")

matches = re.finditer(regex, test_str, re.DOTALL)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

测试re.findall

import re

regex = r"module(.*?)endmodule"

test_str = ("module \n"
    "some text\n"
    "endmodule\n\n"
    "module \n"
    "some other text\n"
    "endmodule")

print(re.findall(regex, test_str, re.DOTALL))

该表达式在此演示的右上角面板中进行了说明,如果您希望进一步探索或简化/修改它,并且在此链接中,您可以根据需要逐步观看它如何与一些示例输入匹配。


推荐阅读