首页 > 解决方案 > 如何使用 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')]

关于如何实现这一目标的任何提示?

标签: regexpython-3.x

解决方案


您可以使用

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+ 个数字

Python演示

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

推荐阅读