1

这是我的代码:

 s="""
    [  8]   0.00-34.53  sec  0.00 Bytes  0.00 bits/sec                  receiver    
    [SUM]   0.00-34.53  sec  2.11 GBytes   624 Mbits/sec                  sender    
    [ 12]   0.00-34.53  sec  0.00 Bytes  0.00 bits/sec                  receive
    [SUM]   0.00-34.75  sec  0.00 Bytes  0.00 bits/sec                  sender
    [SUM]   0.00-34.53  sec  2.11 GBytes   824 Mbits/sec                  sender
    [SUM]   0.00-34.75  sec  0.00 Bytes  0.00 bits/sec                  sender
    """
   items=re.findall("^.[SUM].*sender",s,re.MULTILINE)
     for x in items:
     print(x)

这给出了输出:

[SUM]   0.00-34.53  sec  2.11 GBytes   624 Mbits/sec                  sender
[SUM]   0.00-34.53  sec  2.11 GBytes   824 Mbits/sec                  sender
[SUM]   0.00-34.75  sec  0.00 Bytes  0.00 bits/sec                  sender
[SUM]   0.00-34.75  sec  0.00 Bytes  0.00 bits/sec                  sender

但我想获得以下输出,它以字符串 [SUM] 开头并以字符串 sender 结尾,并且不应显示具有任何 0.00 字节和 0.00 位/秒的行

[SUM]   0.00-34.53  sec  2.11 GBytes   624 Mbits/sec                  sender
[SUM]   0.00-34.53  sec  2.11 GBytes   824 Mbits/sec                  sender
4

2 回答 2

0

使用负前瞻,您可以使用此正则表达式:

reg = "^\s*\[SUM\]\s*[0-9\-\.]+\s+sec(?!\s+0\.00 Bytes).*sender.*"
items=re.findall(reg,s,re.MULTILINE)
for line in items:
    print(line)

这 ?!表示后面的正则表达式不应该是匹配的。更多信息

于 2020-04-02T10:50:12.097 回答
0

这应该对您有用 - 您可能需要针对您的特定需求进行一些调整:

In [151]: regex = "^(\[SUM\](?!.*(([0-9]+\.[0-9]{2}).*){3}.*0\.00).*sender)"

In [152]: items=re.findall(regex,s,re.MULTILINE)
     ...: for x in items:
     ...:     print(x)
     ...:     
('[SUM]   0.00-34.53  sec  2.11 GBytes   624 Mbits/sec                  sender', '', '')
('[SUM]   0.00-34.53  sec  2.11 GBytes   824 Mbits/sec                  sender', '   0.00', '   0.00-34.53  sec  2.11')
于 2020-04-02T09:28:25.623 回答