简体   繁体   中英

Python Regular Expression - match , compare and decide

I have a dictionary which has the different Ip's as Key and its ping result as the Value. i want to proceed with my script only when the ping results passes a certain criteria

Assuming the following as the ping result (dictionary Value):

10 packets transmitted, 10 packets received, 0.00% packet loss

I have created a regular expression and have extracted each of the values as below:

match = re.search(r'(\d+\s* packet\w* transmitted), (\d+\s* packet\w* received), (\d+\.\d+ packet loss)',str,re.M|re.I)

>>> match.group(3)
'10.00% packet loss'

I have extracted the values..

Now i want to write a regular expression with a criteria , through which i will ask the script to proceed with execution only if the packet loss percentage is less than 5 % for each Ip;s on my dictionary.

I can think of again taking the numbers from the packet loss and then comparing but was just wondering if there is a better way to do that?

if any ideas, kindly share ..

You can match just the section of interest, and only for numbers less than 5% with a regular expression:

match = re.search(r' +[0-4]\.\d+% packet loss', str, re.M | re.I)
if match:
    do_stuff_with_match()

However, please note that regular expressions are much slower than numerical comparison, so you may still wish to use the results of the previous parsing.

You don't need a regex:

s = "10 packets transmitted, 10 packets received, 0.00% packet loss"
trans,recv,loss = s.split(",")

print(trans,recv,loss)
('10 packets transmitted', ' 10 packets received', ' 0.00% packet loss')
print(float(loss.split("%")[0] > 5))
False

If you have a dict use all to check if every value is > 5 percent

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