[Tutor] Matching string

Jerry Hill malaclypse2 at gmail.com
Tue Feb 27 17:16:41 CET 2007


On 2/27/07, govind goyal <govindgoyal at gmail.com> wrote:
> Hello,
>
> I want to use a pattern matcing (regular expression) inside "if loop" such
> that if it will find "MBytes" and "Mbits/sec" both at a time  regardless of
> there position in a particular string ,then only it executes code inside "if
> block".


Something like this, perhaps?
>>> myStrings = ["[904]  1.0- 2.0 sec  1.19 MBytes  10.0 Mbits/sec
2.345 ms    0/  850 (0%)",
	     "Server listening on UDP port 5001"]
>>> for myString in myStrings:
	if ("MBytes" in myString and "Mbits/sec" in myString):
		print myString

prints:
[904]  1.0- 2.0 sec  1.19 MBytes  10.0 Mbits/sec  2.345 ms    0/  850 (0%)

Nothing in your example calls for the use of regular expressions, so I
didn't use them.

If you need to use a regular expression to extract the numeric portion
you could do something like this to extract the values you want once
you've identified the strings you need.

import re

myStrings = ["[904]  1.0- 2.0 sec  1.19 MBytes  10.0 Mbits/sec  2.345
ms    0/  850 (0%)",
         "Server listening on UDP port 5001"]

mb_re = re.compile(r'(\d+\.{0,1}\d*) MBytes')
mbps_re = re.compile(r'(\d+\.{0,1}\d*) Mbits/sec')

for myString in myStrings:
    if ("MBytes" in myString and "Mbits/sec" in myString):
            print myString
            mb = mb_re.findall(myString)[0]
            mbps = mbps_re.findall(myString)[0]
            print "MBytes:", mb
            print "Mbits/sec:", mbps


prints:
[904]  1.0- 2.0 sec  1.19 MBytes  10.0 Mbits/sec  2.345 ms    0/  850 (0%)
MBytes: 1.19
Mbits/sec: 10.0

-- 
Jerry


More information about the Tutor mailing list