python - 在两个字符串之间拆分正则表达式 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']
解决方案
我的猜测是您可能想要设计一个类似于以下内容的表达式:
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))
该表达式在此演示的右上角面板中进行了说明,如果您希望进一步探索或简化/修改它,并且在此链接中,您可以根据需要逐步观看它如何与一些示例输入匹配。
推荐阅读
- material-ui - 自定义注册页面重定向到 React-Admin 中的 LoginPage
- flutter - Flutter 中的两列拖放
- identityserver4 - 客户端程序无法在 QuickStarts 基本程序中调用 IdentityServer
- java - 使用 SmallRye 反应式消息动态发布/订阅 MQTT
- c# - 设计asp.net core web api来添加子类/专用对象
- javascript - VueJs Laravel 分页
- javascript - javascript 一次捕获多个错误
- liquibase - 执行 DBMS_AQADM 变更集失败 - 原因:liquibase.exception.DatabaseException:ORA-00900:无效的 SQL 语句
- python - NoSuchElementException:消息:没有这样的元素:使用 Selenium 和 Python 抓取前 20 名持有者时无法定位元素错误
- html - 如何仅在屏幕较小时向右浮动,而在屏幕较大时向左浮动?