python - Python多行模式搜索
问题描述
我有以下文本,我需要对其进行解析以提取所有三个值的组。对于这个特定示例,我需要这样的输出: [1,1,1],[2,2,2],[3,2,3],[4,2,4] 我试图使用这个 reg expr :
re.findall(r'measId \d+,[\n\r]measObjectId \d+[\n\r],reportConfigId \d+',output)
但它总是返回零结果。我已经尝试了多种带有 re.MULTILINE 标志的组合,但没有一个,但没有区别。我究竟做错了什么?有什么建议吗?
measIdToAddModList {
{
measId 1,
measObjectId 1,
reportConfigId 1
},
{
measId 2,
measObjectId 2,
reportConfigId 2
},
{
measId 3,
measObjectId 2,
reportConfigId 3
},
{
measId 4,
measObjectId 2,
reportConfigId 4
}
解决方案
Here is the most naive solution. It works only if exactly three fields are present:
re.findall(r'\{\s+(\w+\s+\d+),\s+(\w+\s+\d+),\s+(\w+\s+\d+)\s+}', s)
#[('measId 1', 'measObjectId 1', 'reportConfigId 1'),
# ('measId 2', 'measObjectId 2', 'reportConfigId 2'),
# ('measId 3', 'measObjectId 2', 'reportConfigId 3'),
# ('measId 4', 'measObjectId 2', 'reportConfigId 4')]
Explanation:
\{ # Opening curly brace
\s+ # One or more spaces
(\w+\s+\d+) # word, spaces, digits
,\s+ # comma, spaces
(\w+\s+\d+)
,\s+
(\w+\s+\d+)
\s+ # spaces
} # Closing curly brace
推荐阅读
- php - 使用 DomDocument 将 HTML、CSS 和 JavaScript 从文件中分离出来
- google-api - Google API 访问令牌含义
- php - 以编程方式为 WooCommerce 中的特定可变产品设置最小、最大和步长数量
- docker - nginx 从 foo.bar/app 正确反向加载资产
- javascript - 根据 Acrobat 中其他组合框的结果填充组合框
- php - 为什么 Laravel 网站在直播服务器上运行在两条不同的路径上,路径相同
- python - 基于另一个数据帧 Python 和 Pandas 从数据帧中采样
- reactjs - 为什么我不能在使用 getServerSideProps 或 getInitialProps 的组件的子组件中使用 NextJS 的 useRouter?
- docker - 使用 WORKDIR 命令时 Dockerfile 无法正常工作?
- c - cast 和 mask 的区别