[Tutor] Problems with Gauge Bar.

greg whittier greg at thewhittiers.com
Sun Aug 10 17:41:23 CEST 2008


On Sun, Aug 10, 2008 at 10:38 AM, Olrik Lenstra <o.lenstra at gmail.com> wrote:
> That bit of code doesn't make a lot of sense to me so far.
> I don't see how that could "X" out a public address.
>
> (I do appreciate the help!)
>
> Regards,
> Olrik
>

r = re.compile(r"(\d+)\.(\d+)\.\d+\.\d+")
m = re.search(lines[i])   # search returns a match object

if m:   # the match object will be "None" if there is no match

  n1, n2 = m.groups()  # n1, and n2 contain the strings corresponding
to the parts
                                # of the regexp in parentheses above
                                # e.g., n1 == '192' and n2 == '168'
  n1 = int(n1)
  n2 = int(n2)  # convert them to integers  (I used  the "map" trick
before to do this in one line)

  # n1, n2 now have the first two numbers of the IP address

  # Once you have n1, n2, you can check what range the ip is in and
act accordingly.

  # I left this out before, but here's how you might do the check
  if ( n1 == 10 or (n1 == 192 and n2 == 168)
      or (n1 == 169 and n2 == 254) or (n1 == 172 and n2 >= 16 and n2 <= 31)):
      lines[i] =  r.sub("xxx.xxx.xxx.xxx",lines[i])   # using sub is a
little more compact

Check out the python regular expression howto -
http://www.amk.ca/python/howto/regex/

Greg


More information about the Tutor mailing list