[英]How to match a number in middle using python regular expression?
我试图为以下命令输出输入通过/失败标准。
router-7F2C13#show app stats gmail on TEST/switch1234-15E8CC
--------------------------------------------------------------------------------
APPLICATION BYTES_IN BYTES_OUT NUM_FLOWS
--------------------------------------------------------------------------------
gmail 0 0 0
--------------------------------------------------------------------------------
router-7F2C13#
我只需要匹配“ NUM_FLOWS”。 如果其为“零”,则将其视为失败。 如果其“大于或等于1”,则将其视为PASS。
FAIL criteria example:
======================
router-7F2C13#show app stats gmail on TEST/switch1234-15E8CC
--------------------------------------------------------------------------------
APPLICATION BYTES_IN BYTES_OUT NUM_FLOWS
--------------------------------------------------------------------------------
gmail 0 0 0
--------------------------------------------------------------------------------
router-7F2C13#
PASS criteria example: (Greater than or equal to 1)
======================
router-7F2C13#show app stats gmail on TEST/switch1234-15E8CC
--------------------------------------------------------------------------------
APPLICATION BYTES_IN BYTES_OUT NUM_FLOWS
--------------------------------------------------------------------------------
gmail 0 0 1
--------------------------------------------------------------------------------
router-7F2C13#
请指导我如何执行此操作。
NUM_FLOWS\n-+[\s\S]*?(\d+)\s*-+
您可以尝试此操作。
参见演示。
https://www.regex101.com/r/bC8aZ4/7
x="""router-7F2C13#show app stats gmail on TEST/switch1234-15E8CC
--------------------------------------------------------------------------------
APPLICATION BYTES_IN BYTES_OUT NUM_FLOWS
--------------------------------------------------------------------------------
gmail 0 0 0
--------------------------------------------------------------------------------
router-7F2C13#
---------------------------------------------------------------
router-7F2C13#"""
if int(re.findall(r"NUM_FLOWS\n-+[\s\S]*?(\d+)\s*-+",x)[0]):
print "pass"
else:
print "fail"
由于这是命令输出,因此您可以将命令的输出通过管道fileinput
到Python脚本中,并使用fileinput
模块进行处理:
import fileinput
for line in fileinput.input():
if fileinput.filelineno() == 5:
# split the line on whitespace, and take the last item.
x = int(line.split()[-1])
print('PASS' if x else 'FAIL')
break # so it won't process more lines past 5
结果为pass.xxx
包含通过标准,而fail.xxx
包含失败标准:
c:\> type fail.xxx | check.py
FAIL
c:\> type pass.xxx | check.py
PASS
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.