re Challenge: More Compact?

Quinn Dunkan quinn at regurgitate.ugcs.caltech.edu
Mon Jul 16 00:29:08 EDT 2001


On Mon, 16 Jul 2001 00:58:46 GMT, Tim Hammerquist <tim at vegeta.ath.cx> wrote:
>Tim Daneliuk <tundra at tundraware.com> wrote:
>> The following re is (I think) the description of a legitimate IP addess in
>> "quad" format (IPV4).  My question is, can it be made even shorter?
>> 
>> ipquad   = r"^((\d\d?\d?\.){3}(\d\d?\d?))$"
>
>from 'Mastering Regular Expressions', p.124:
>
>'^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.\
>([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$'

How about:

for o in '.'.split(ip_addr):
    assert 0 <= int(o) <= 255, 'ip octet not a byte in "%s"' % ip_addr

Re's can be handy, but their usefulness can trick you into trying to use them
for things for which they're not suitable.



More information about the Python-list mailing list