For example, I am having a column storing data like this.
Apple
12.5.126.40
Smite
Abby
127.0.0.1
56.5.4.8
9876543210
Notes
How to select out only the rows with data in IP format?
I have tried with '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$'
but I have no idea why it also matches 9876543210
you could also use the useful function inet_aton()
This may not be the most efficient way, and it's not technically regex, but it should work:
You're going to need to use
REGEXP
to match the IP address dotted quad pattern.Technically, this will match values that are not valid IP addresses, like
999.999.999.999
, but that may not be important. What is important, is fixing your data such that IP addresses are stored in their own column separate from whatever other data you have in here. It is almost always a bad idea to mix data types in one column.Another method is to attempt to convert the IP address to a long integer via MySQL's
INET_ATON()
function. An invalid address will returnNULL
.This method is likely to be more efficient than the regular expression.
You may embed it in a
WHERE
condition like:WHERE INET_ATON(thecolumn) IS NOT NULL
IS_IPV4()
is a native mysql function that lets you check whether a value is a valid IP Version 4.I don't have data, but I reckon that this must be the most solid and efficient way to do this.
There are also similar native functions that check for IP Version 6 etc.
Lengthy but works fine: