user3515524
user3515524

Reputation: 23

regex for list of ip addresses

I want to match a string containing either '*' or a comma separated list of IPv4 addresses.

The following works for one IP or a star:

/^(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|*)$/

And I've tried to adopt this for having a list of IPs or a star:

/^(?:^|, )(?:(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|*)$/

But it doesn't works as expected.

Could you please help me?

thx, Thomas

Upvotes: 1

Views: 4089

Answers (1)

Paul S.
Paul S.

Reputation: 66324

Because you were being specific about the accepted numbers for the IPs,

/^\*$|^(?:\d|1?\d\d|2[0-4]\d|25[0-5])(?:\.(?:\d|1?\d\d|2[0-4]\d|25[0-5])){3}(?:\s*,\s*(?:\d|1?\d\d|2[0-4]\d|25[0-5])(?:\.(?:\d|1?\d\d|2[0-4]\d|25[0-5])){3})*$/
// * or   IP=   0-255                    .0-255 (3 more times)           then (, IP) 0 or mote times

I'd only use a RegExp like this if you must check validity with just one RegExp, because it may be much clearer to break it down into several steps, otherwise.

// some func
var reIP = /^(?:\d|1?\d\d|2[0-4]\d|25[0-5])(?:\.(?:\d|1?\d\d|2[0-4]\d|25[0-5])){3}$/,
    tokens = str.split(/\s*,\s*/), i;
for (i = 0; i < tokens.length; ++i)
    if (!reIP.test(tokens[i]))
        return false;
return true;

Upvotes: 2

Related Questions