简体   繁体   中英

How to match “0 0 0” exactly using python regular expression?

I am trying to match all "ALL ZEROs" from the following command output.

router-7F2C13#show app stats gmail on TEST/switch1234-15E8CC
--------------------------------------------------------------------------------
     APPLICATION           BYTES_IN         BYTES_OUT           NUM_FLOWS
--------------------------------------------------------------------------------
  gmail                0                 0                  0
--------------------------------------------------------------------------------
router-7F2C13#

I need to meet the following requirements:

I tried with following code:

x="""router-7F2C13#show app stats gmail on TEST/switch1234-15E8CC
--------------------------------------------------------------------------------
     APPLICATION           BYTES_IN         BYTES_OUT           NUM_FLOWS
--------------------------------------------------------------------------------
  gmail                0                 0                  0
--------------------------------------------------------------------------------
router-7F2C13#"""

def pass_fail_criteria(x):
    if int(re.findall(r"NUM_FLOWS\n-+[\s\S]*?(\d+)\s*-+"):
        print "FAIL"
    else:
        print "PASS"

print pass_fail_criteria(x)     

But its throws following error:

C:\Users\test\Desktop>python test_regexp.py
  File "test_regexp.py", line 17
    if int(re.findall(r"NUM_FLOWS\n-+[\s\S]*?(\d+)\s*-+"):
                                                         ^
SyntaxError: invalid syntax

C:\Users\test\Desktop>

Can anyone please help me to fix this?

Is it possible to match only all zero's with exact spaces?

You might try a regex like

\s*\w+\s+(\d+)\s+(\d+)\s+(\d+)

This would seem to match

gmail    0   0   0

An alternative (at your request) is to match the literal 0 's. Just replace the digit match with 0:

\s*\w+\s+(0)\s+(0)\s+(0)

Note that the (parentheses) are for grouping, and may not be necessary depending on how you'll be using the regex. If you're just testing for a match, you can drop them.

Then you should probably write a function to ensure the matches are all 0.

You might take a look at debuggex .

正则表达式可视化

Debuggex Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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