And the clouds parted, and Wiggins d Anconia said...
>
>
> > Rick Bragg wrote:
> > > Hi,
> > >
> > > I want to write a script that will test the contents of a file.
> > >
> > > The file being tested will pass only if it contains nothing more
> than an
> > > ip address on one line. Does anyone have a sample of a simple regex to
> > > accomplish this?
> >
> > /\d+\.\d+\.\d+\.\d+\n?/s
> >
>
> Beware of insufficient regexes in regex clothing. The above will
> certainly find one or more digits followed by a dot, followed by one or
> more digits followed by a dot, etc. But it does *NOT* match an IP
> address...
>
> /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/
>
> Is at least closer, but it is still not sufficient, as IP addresses are
> bounded, I believe, at 255 so 336.47.894.0, will match the above, but is
> not a valid IP address.
>
> How strict do you need to be, how sure are you about the data in the files?
>
Good point.
At it's most basic, to match any valid IPv4 address alone on a line, I would
use
/\A((1?\d{1,2}|2([0-4]\d|5[0-5]))\.){3}(1?\d{1,2}|2([0-4]\d|5[0-5]))\z/
Which will match a string containing only a dotted quad from 0.0.0.0 to
255.255.255.255, inclusive. Note that I'm assuming the string in
question contains the _entire_ contents of the file.
A couple of things to note, though:
* A valid IP is actually any 32 bit integer from 0 to 4294967295 (try
putting 3639555427 in Mozilla (or supposedly any other well-behaved
browser... in other words, _not_ IE)... it will take you to Google
because that number is actually 216.239.53.99 - the address for
www.google.com - in base-10).
* This pattern doesn't exclude RFC1918 reserved addresses (10/8,
172.16/12, and 192.168/16), or multicasts.
* It doesn't take netmasks into account. 1.2.3.255/16 is a valid
host address, while 1.2.3.255/24 is not (it's a broadcast).
Taking these sorts of things into account could make for a bit hairier
solution. ;) Caveat user.
/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\
| Brian Gerard I'm writing an unauthorized autobiography. |
| First initial + 'lists' |
| at technobrat dot com |
\______________________________________________________________________/
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]