What regex can I use to match any valid IP-address

2019-04-06 11:02发布

What regex can I use to match any valid IP-address represented in dot-decimal notation?

10条回答
ゆ 、 Hurt°
2楼-- · 2019-04-06 11:42
聊天终结者
3楼-- · 2019-04-06 11:44

Not sure why I don't see this one around anywhere, it's short, concise, and awesome.

([0-9]{1,3}\.){3}[0-9]{1,3}
查看更多
Deceive 欺骗
4楼-- · 2019-04-06 11:46

For IPv4 in an A.B.C.D (decimal) format, as a one-liner:

(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])

If nothing follows the address on the line, it can be contracted to:

(?:(?:[01]?\d?\d?|2[0-4]\d|25[0-5])(?:\.|$)){4}

Have fun.

查看更多
神经病院院长
5楼-- · 2019-04-06 11:47

I like this one ... pretty much as Steve Hajducko's but using quoted reg ex which rooooock!

my $ip = '120.140.255.254'; # for example

my $ipno = qr/
    2(?:5[0-5] | [0-4]\d)
    |
    1\d\d
    |
    [1-9]?\d
/x;

if ( $ip =~ /^($ipno\.){3}$ipno$/ ){
    print "IP OK\n";
};

I went for an interview at Arm in Cambridge, UK. They asked me to write one on the board and I wrote some lame one .. and later ... brooding on my poor attempt set out to make a better one. Driven by failure? Or maybe just really irritated by it. I still got the job :)

查看更多
登录 后发表回答