mysql 正则 去0,MySQL正则表达式从IPv4替换0

I cannot make a mysql regexp which would remove zeros in the beggining of each 3 number sequences of IPv4.

The problem is that the validation should be provided on database level and I don't know how to formulate the regex which would replace all 0., 00., .0, .00 with emtpy string from my IPv4.

I want my regex to do something like that :

If I have 012.123.123.023 entering the database it should be saved as 12.123.123.23

Thank you !

解决方案

By utilizing the MySQL functions INET_ATON() and INET_NTOA() you can reliably convert an incoming IPv4 address which has leading zeros into the same string without leading zeros. Wrap INET_ATON() with INET_NTOA() to convert the IP address first to its integer value, and then back to a dotted quad.

IP with leading zeros in various places:

mysql> SELECT INET_NTOA(INET_ATON('001.110.011.111'));

+-----------------------------------------+

| INET_NTOA(INET_ATON('001.110.011.111')) |

+-----------------------------------------+

| 1.110.11.111 |

+-----------------------------------------+

And without leading zeros for comparison:

mysql> SELECT INET_NTOA(INET_ATON('1.110.11.111'));

+--------------------------------------+

| INET_NTOA(INET_ATON('1.110.11.111')) |

+--------------------------------------+

| 1.110.11.111 |

+--------------------------------------+

Note: This will return NULL if the input IP address was not a valid address. It won't return the original string or strip leading zeros from a bad IP address:

Faulty IP address with leading zeros:

mysql> SELECT INET_NTOA(INET_ATON('888.777.123.123'));

+-----------------------------------------+

| INET_NTOA(INET_ATON('888.007.123.123')) |

+-----------------------------------------+

| NULL |

+-----------------------------------------+

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值