我正在尝试从通过正则表达式给出的大量数据中提取一些有用的数据。
示例字符串:
test 1:
hello op1 yviphf
hello op2 vipqwe
test 2:
hello op3
hello op4 vipgt
hello op5 zcv
上面包含 2 个测试编号,但有几个。我想提取 op1、op2、op3、op4、op5 以及相应的测试编号。每个测试中的操作数可以不同。
以下是我尝试编写的模式,但没有帮助:
test\s(\d+).*?(?:hello\s+(\S+).*?\n)+
输出可能是列表的列表。主列表将第一个元素作为测试编号,第二个元素可能是包含所有操作的列表。
请您参考如下方法:
我建议采用基于正则表达式的三步法。
- 首先,使用
r'test\s*(\d+)'和re.findall获取所有测试数字(这只会获取数字列表作为\d+子模式在捕获组内) - 其次,使用
test\s*\d+正则表达式拆分输入字符串以获得带有hello代码的子部分并运行hello\s+(\S+ )(或(?m)^hello\s*(\S+)如果hello从行首开始)每个非空 block 上的正则表达式(同样,re.findall只会获取\S+子匹配项,因为它包含在捕获组中) - 将列表合并为元组列表。
import re
test_str = "test 1:\nhello op1 yviphf\nhello op2 vipqwe\ntest 2:\nhello op3\nhello op4 vipgt\nhello op5 zcv"
res1 = [y for y in re.findall(r'test\s*(\d+)', test_str) if y]
res2 = [re.findall(r'(?m)^hello\s*(\S+)', b) for b in re.split(r'test\s*\d+', test_str) if b]
print(zip(res1, res2))
结果:[('1', ['op1', 'op2']), ('2', ['op3', 'op4', 'op5'])]
