gpt4 book ai didi

python - 在正则表达式 python 上分割两个字符串,但包含使用 re.split 并返回一个列表

转载 作者:行者123 更新时间:2023-12-01 00:46:07 25 4
gpt4 key购买 nike

我正在尝试分割文件中的一段文本,格式如下:

module 
some text
endmodule

module
some other text
endmodule

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

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

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

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

但它不会 split 任何东西......

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

['模块\n sometext\n endmodule', '模块\n someothertext\n endmodule']

最佳答案

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

module(.*?)endmodule

但不确定。

使用 re.finder 进行测试

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))

该表达式在 this demo 的右上角面板中进行了解释,如果您想进一步探索或简化/修改它,请在this link中,如果您愿意,您可以逐步观察它如何与一些示例输入进行匹配。

关于python - 在正则表达式 python 上分割两个字符串,但包含使用 re.split 并返回一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56961676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com