Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Regular Expression to Match the Whole line

Tags:

python

regex

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 output is:

64 bytes from 33.33.33.33: icmp_seq=9 ttl=254 time=1.011 ms

--- 33.33.33.33 ping statistics ---
10 packets transmitted, 10 packets received, 0.00% packet loss

I tried writing a regex matching packet loss and tried to fetch the complete line but could not make it work.

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

But this output printed only:

00% packet loss
00% packet loss
like image 847
user596922 Avatar asked Dec 12 '22 02:12

user596922


2 Answers

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$'
like image 69
Ryan Haining Avatar answered Jan 10 '23 14:01

Ryan Haining


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.

like image 35
Matt W Avatar answered Jan 10 '23 15:01

Matt W