regex - 如何使用 re.findall() 查找由“=”符号分隔的单词
问题描述
我正在阅读一个包含以下内容的文件:
//some text
Integral of Qr over area magnitude of patch B1_TE16_B1_TE4[0] = -1073.40295735
//some more text
Integral of Qr over area magnitude of patch B1_TE16_B1_TE11[1] = 1099.13456362
//some more text
Integral of Qr over area magnitude of patch B1_TE16_B1_TE13[2] = 1025.13456362
我使用re.findall('Integral of Qr over area magnitude of patch ([\w\.-]+)')
并且能够在'B1_TE16...'
没有索引号的情况下找到所有三个名称。
现在,我想要实现的是下一个输出:
[('B1_TE16_B1_TE4[0]', '-1073.40295735'), ('B1_TE16_B1_TE11[1]', '1099.13456362'), ('B1_TE16_B1_TE13[2]', '1025.13456362')]
关于如何实现这一目标的任何提示?
解决方案
您可以使用
r'Integral of Qr over area magnitude of patch ([\w.-]+\[\d+])\s*=\s*(-?\d*\.?\d+)'
查看正则表达式演示
细节
([\w.-]+\[\d+])
- 第 1 组:一个或多个单词,.
或-
字符[
,,1 个或多个数字,然后是]
\s*=\s*
-=
用 0+ 个空格括起来(-?\d*\.?\d+)
- 第 2 组:一个可选-
的,0+ 个数字,一个可选的.
,然后 1+ 个数字
import re
s = """//some text
Integral of Qr over area magnitude of patch B1_TE16_B1_TE4[0] = -1073.40295735
//some more text
Integral of Qr over area magnitude of patch B1_TE16_B1_TE11[1] = 1099.13456362
//some more text
Integral of Qr over area magnitude of patch B1_TE16_B1_TE13[2] = 1025.13456362"""
rx = r'Integral of Qr over area magnitude of patch ([\w.-]+\[\d+])\s*=\s*(-?\d*\.?\d+)'
print(re.findall(rx, s))
# => [('B1_TE16_B1_TE4[0]', '-1073.40295735'), ('B1_TE16_B1_TE11[1]', '1099.13456362'), ('B1_TE16_B1_TE13[2]', '1025.13456362')]
推荐阅读
- reactjs - 如何将数据从道具更新到 d3 函数?
- python - PyCodeStyle - Sublime Text 3 - 注释行长度
- r - 如何将 autoplot + autolayer 与 xts 对象一起使用?
- javascript - 输入小数时如何使用正则表达式保留0开始字符?
- regex - 将正则表达式结果保存到变量
- java - JAVA:命名数组索引
- r - 忽略一个 magrittr 管道值并将其传递
- java - 如何删除 Vaadin 8 ComboBox 中的按钮?
- c - 在 C 中通过套接字定期发送数据
- c++ - 将 SDL 2 VS Code 项目与 Easy C++ 项目链接