user1191255
user1191255

Reputation:

MySQL select based on regular expression

In MySQL, I need to select all rows where a field is not an IP address (e.g. 12.32.243.43). Can this be done with MySQL only?

For example: I tried the following but it doesn't match.

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

Upvotes: 0

Views: 2573

Answers (2)

Michael Buen
Michael Buen

Reputation: 39393

If using regular expression is not a requirement, this shall deliver the solution:

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


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

Sample data:

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');

Here are the list of invalid ip:

STRINGBASEDIP
0.0.0.300
0.0.0.-1
0.0.0.A
400.168.0.1
12.32.243.430

Live test: http://www.sqlfiddle.com/#!2/2a4ec/1

Upvotes: 2

Menztrual
Menztrual

Reputation: 41587

Sure can. You would be looking for something like:

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

Upvotes: 2

Related Questions