Python Regular Expression to Match the Whole line

前端 未结 3 1529
天命终不由人
天命终不由人 2021-01-13 12:21

I\'m new to scripting and have been reading about how to use regular expressions.

I want to fetch the complete line matching a pattern.

my ouptut is:

相关标签:
3条回答
  • 2021-01-13 12:43

    If you want to print the whole line you can just iterate through the lines and print those that contain 'packet loss'.

    for line in lines:
        if line.find('packet loss') != -1:
            print line
    
    0 讨论(0)
  • 2021-01-13 12:47

    Try

    cmd = re.search('^.*\d*% packet loss.*$', ping_result[int(i)], re.M|re.I)
    print cmd.group()
    

    '^' and '$' match the start and end of a line, respectively. You also don't need the parentheses unless you want to select the packet loss separately.

    0 讨论(0)
  • 2021-01-13 12:49

    First off, you want to use raw strings when providing the regex string, this is done by prefixing the string with an r, otherwise escape sequences will be absorbed.

    \d will match digits, but not the dot that appears between them. Since you want that as a group you'll need r'(\d+\.\d+)'

    (if you use search instead of match then you don't need to worry about this):Finally you'll need something to capture everything in the line up to that number as well, which can be done easily with .*, capturing any amount of characters. Your search pattern becomes:

    r'.*(\d+\.\d+)% packet loss'
    

    If you want to be explicit about the start and end of the line, then use the ^ (start) and $ (end) special characters

    r'^.*(\d+\.\d+)% packet loss$'
    
    0 讨论(0)
提交回复
热议问题