【问题标题】:MySQL select based on regular expressionMySQL 基于正则表达式的选择
【发布时间】:2012-04-29 04:48:12
【问题描述】:

在 MySQL 中,我需要选择字段不是 IP 地址的所有行(例如 12.32.243.43)。这只能用 MySQL 完成吗?

例如:我尝试了以下但不匹配。

select * from mytable where field not like '%.%.%.%' 

【问题讨论】:

标签: mysql sql


【解决方案1】:

当然可以。你会寻找类似的东西:

SELECT * FROM `table` WHERE NOT( some_field REGEXP '^[0-9+]\.[0-9]+\.[0-9+]\.[0-9+]')

【讨论】:

  • regexp 无法覆盖无效的 IP 地址:12.32.243.299
  • @MichaelBuen:它可以,但不是很优雅:^(([01]\d{0,2}|2[0-4]?\d?|25[0-5]|[3-9]\d?)\.){3}([01]\d{0,2}|2[0-4]?\d?|25[0-5]|[3-9]\d?)$
【解决方案2】:

如果不要求使用正则表达式,这将提供解决方案:

select stringBasedIp from x
where inet_aton(stringBasedIp) is null;


select stringBasedIp, (inet_aton(stringBasedIp) is null) as isInvalidIp
from x;

样本数据:

create table x(stringBasedIp varchar(16));

insert into x values
('255.255.255.255'),
('0.0.0.0'),
('0.0.0.300'),
('0.0.0.-1'),
('0.0.0.A'),
('192.168.0.1'),
('400.168.0.1'),
('12.32.243.43'),
('12.32.243.430');

以下是无效ip列表:

STRINGBASEDIP
0.0.0.300
0.0.0.-1
0.0.0.A
400.168.0.1
12.32.243.430

现场测试:http://www.sqlfiddle.com/#!2/2a4ec/1

【讨论】:

    猜你喜欢
    • 2016-01-11
    • 1970-01-01
    • 2011-05-14
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 2012-06-23
    • 1970-01-01
    相关资源
    最近更新 更多