开发者

Scrubbing IPv4 dotted-quad addresses in SQL

开发者 https://www.devze.com 2022-12-25 03:10 出处:网络
Given a table containing dotted quad IPv4 addresses stored as a VARCHAR(15), for example: ipv4 --------------

Given a table containing dotted quad IPv4 addresses stored as a VARCHAR(15), for example:

     ipv4
--------------
 172.16.1.100
 172.16.50.5
 172.30.29.28

what's a convenient way to SELECT all "ipv4" fields with the final two octets scrubbed, so that the above would become:

    ipv4
------------
 172.16.x.y
 172.16.x.y开发者_开发百科
 172.30.x.y

Target RDBMS is postgresql 8.4, but the more portable the better!

Thanks.

UPDATE: while I do appreciate (and do upvote) slick INET/CIDR answers, I am looking to produce a string output with non-numeric characters substituted for the final two octets. (And, again, the more portable the better!)


For postgres:

select regexp_replace('172.16.1.100', E'(.\\d+){2}$', '.x.y');


If you use the Postgres inet type, then you can do this with the inet operators, eg. <<= means 'is contained within'. I suspect that something lik the following will do what you need:

select my_ipaddress & inet '255.255.0.0' from my_ip_table;

Manual reference: http://www.postgresql.org/docs/8.4/static/functions-net.html


Conventional is to convert column type to inet/cidr

EDIT: With this native data type there's quite a few specific functions that perform much better than any string manipulation.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号