如何使用python正则表达式匹配中间的数字?

时间:2015-01-27 06:24:22

标签: python regex python-2.7

我正在尝试为以下命令输出设置PASS / FAIL标准。

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”那么它将被视为通过。

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#

请指导我如何做到这一点。

2 个答案:

答案 0 :(得分:1)

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"

答案 1 :(得分:1)

由于这是命令输出,您可以将命令的输出传递给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