简体   繁体   English

在多行文本中捕获多个字符串

[英]Catch multiple string occurrences in multiline text

Iv'e been at it for some time now, I'm trying to extract a number of values from a string pattern in a multiline text using re.findall with no luck. 我已经花了一段时间了,我正在尝试使用re.findall从多行文本中的字符串模式中提取一些值,但是没有运气。

text: 文本:

RX[0]
qpn : 0x48
cqn : 0x80
rxBytes : 179531811
rxPackets : 296242
rxPacketsDropped : 0
rxCheckSumOk : 225257
rxCheckSumNone : 200
RX[1]
qpn : 0x49
cqn : 0x81
rxBytes : 0
rxPackets : 0
rxPacketsDropped : 0
rxCheckSumOk : 0
rxCheckSumNone : 0**

i need to extract the index -> RX[index] and the rxPackets : value 我需要提取索引-> RX[index]rxPackets : value

if i split to sections than i can use - 如果我拆分为多个部分,可以使用-

re.findall('RX\[(\d+)\].*rxPackets\s*:\s*(\d+)', section, re.DOTALL)

but i'm looking to do this with a single regex pattern. 但是我正在寻找一个正则表达式模式。 can any one help me shed some light on how to do this? 谁能帮助我阐明如何执行此操作?

This works: 这有效:

>>> txt='''\
... RX[0]
... qpn : 0x48
... cqn : 0x80
... rxBytes : 179531811
... rxPackets : 296242
... rxPacketsDropped : 0
... rxCheckSumOk : 225257
... rxCheckSumNone : 200
... RX[1]
... qpn : 0x49
... cqn : 0x81
... rxBytes : 0
... rxPackets : 0
... rxPacketsDropped : 0
... rxCheckSumOk : 0
... rxCheckSumNone : 0**
... '''
>>> import re 
>>> re.search(r'RX\[(\d+)\].*?rxPackets\s+:\s+(\d+)', txt, re.S).groups()
('0', '296242')

Or, with findall: 或者,使用findall:

>>> re.findall(r'RX\[(\d+)\].*?rxPackets\s+:\s+(\d+)', txt, re.S)
[('0', '296242'), ('1', '0')]

Compare with using the greedy form of .* : 与使用.*的贪婪形式进行比较:

>>> re.findall(r'RX\[(\d+)\].*rxPackets\s+:\s+(\d+)', txt, re.S)
[('0', '0')]

Which you can see visually here for greedy and not greedy 您可以在这里直观看到贪婪不是贪婪

I am too stupid to use a regex to solve this. 我太傻了,无法使用正则表达式来解决这个问题。

rxDict = dict()
key = ''
for line in lines:
    if 'RX' in line:
    key = line.split('[')[-1].split(']')[0]
    if key != '':
       if 'rxPackets' in line:
            rxDict[key] = line.split(':').strip()
            key = ''

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM