Python regular expression to pick values in a string

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kaf3773
    New Member
    • Jan 2012
    • 20

    Python regular expression to pick values in a string

    Hi
    I have the output below stored in a variable called outping. I am trying to pick the values in bold into two variables using python regular expressions. i will appreciate your help. Thanks

    Type escape sequence to abort.
    Sending 100, 100-byte ICMP Echos to 192.168.1.8, timeout is 2 seconds:
    !!!!!!!!!!!!!!! !!!!!!!!!!!!!!! !!!!!!!!!!!!!!! !!!!!!!!!!!!!!! !!!!!!!!!!
    !!!!!!!!!!!!!!! !!!!!!!!!!!!!!!
    Success rate is 100 percent (100/100), round-trip min/avg/max = 1/3/12 ms
    switch1B#

    Here is the code i am trying to use
    Code:
    patt = re.compile(r"(Success rate)", re.MULTILINE)     
    m = re.search(patt, outping)
    print m.group(1)
  • dwblas
    Recognized Expert Contributor
    • May 2008
    • 626

    #2
    I would do it like this since it is understandable and can be easily debugged and/or broken down.
    Code:
    test_string="Success rate is 100 percent (100/100), round-trip min/avg/max = 1/3/12 ms"
    if test_string.startswith("Success"):
        test_list=test_string.split()
        percent = ""
        for ctr, word in enumerate(test_list):
            if word == "percent":
                percent = test_list[ctr-1]  ## previous word
    
    print percent, test_list[-2].split("/")[-1]

    Comment

    Working...