To answer this, I did the following (all of the code below is available on the fiddle here):
CREATE TABLE test
(
IP INET
);
and
INSERT INTO test VALUES
('134.34.34.34'::INET),
('172.24.12.20'::INET);
Now, you appear to have your IP addresses as strings. This is not the best idea - it's always best to use the appropriate data type (operators, comparisons, sorting, indexing, correct values enforced automatically), but in this case, we'll just have to use strings.
As pointed out by @ÁlvaroGonzález
, this works nicely with IP addresses:
SELECT
*
FROM test
WHERE ip <<= '172.24.12/24'::INET;
Result:
ip
172.24.12.20
We'll just have to use the PostgreSQL cast operator (::
) to convert these to strings as follows:
SELECT
ip
FROM test
WHERE ip::TEXT ~ '172\.24\.12\.[0-2]{1}[0-9]{1,2}'
Result:
ip
172.24.12.20
The regex above isn't the best - you could spend all day searching for regexes - for example this:
SELECT
ip
FROM test
WHERE ip::TEXT ~ '172\.24\.12\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])';
will also work and is more thorough. It's up to you to choose which regex covers your needs.