简体   繁体   English

正则表达式 python:仅查找第二个和第三个字符串模式

[英]Regular expression python: Find just second and third string pattern

for the following text I want to get second and third pattern of "Error:....." (see bold text).对于以下文本,我想获得“错误:.....”的第二个和第三个模式(见粗体文本)。

Basically I need to print out from text below:基本上我需要从下面的文本中打印出来:

Error: Calculated last average: 150.34365623971, read last average: 132, Tolerance: 12

Following text:以下文字:

Error: Register 3.5.0 -------------- [Device type: Am500T_Elektra; Device Id: 00000000]

Error: Calculated last average: 150.34365623971, read last average: 132 -------------- [Device type: Am500T_Elektra; Device Id: 00000000]

Error: Tolerance: 12 -------------- [Device type: Am500T_Elektra; Device Id: 00000000]

I got stuck here:我被困在这里:

re.compile(r'Error: (.+ -)').findall

Any hint or advice how to continue?任何提示或建议如何继续?

Assuming that only the values change:假设只有值改变:

regex = re.compile(r'Error: Calculated last average: \d+\.?\d+?, read last average: \d+, Tolerance: \d+')
re.match(regex, text) 

The \d+\.?\d+? \d+\.?\d+? means match any digit at one or more times, followed by an optional dot (the decimal point), followed by another optional digit match.表示一次或多次匹配任何数字,后跟一个可选的点(小数点),然后是另一个可选的数字匹配。 This way, even if the average is not a floating point number, it will still match.这样,即使平均值不是浮点数,它仍然会匹配。

For the other values, I have kept the regex as \d+ , assuming that these will always be integers.对于其他值,我将正则表达式保留为\d+ ,假设它们始终是整数。 You may need to change these as well, as the case may be.您可能还需要更改这些,视情况而定。

Could try using a re.sub可以尝试使用 re.sub

>>> import re
>>> text = '''
... Error: Register 3.5.0 -------------- [Device type: Am500T_Elektra; Device Id: 00000000]
...
... Error: Calculated last average: 150.34365623971, read last average: 132 -------------- [Device type: Am500T_Elektra; Device Id: 00000000]
...
... Error: Tolerance: 12 -------------- [Device type: Am500T_Elektra; Device Id: 00000000]
... '''
>>>
>>> regex = re.compile(r"(?m)(?:\A\s*.*\s*|^Error:\s*|(\s*--+.*\s*(?=^Error:))|\s*--+.*\s*|(?![\S\s]*?(?:^Error:|--+))[\S\s]+)")
>>>
>>> print ( "Error: " + regex.sub(lambda x: ", " if (x.group(1)) else "", text ) )
Error: Calculated last average: 150.34365623971, read last average: 132, Tolerance: 12

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

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