How to filter a character followed by numbers string pattern in PostgreSQL?
-
16-03-2021 - |
Domanda
Back in SQL Server, I use the command below to get the matching string pattern of #1234
from the column called Number
SELECT [m].[Number]
FROM [Boats] AS [m]
WHERE [m].[Number] LIKE N'[#][0-9][0-9][0-9][0-9]'
Now in Postgres, I have tried using the command below, but no luck:
SELECT m.Number
FROM Boats AS m
WHERE m.Number ILIKE '#[0-9][0-9][0-9][0-9]'
Any idea what pattern expression should I use to get the correct filter?
Soluzione
You can use the operator ~
that uses the full power of regular expressions
select *
from (values ('#1234'), ('#3333'), ('#abcd')) as boats (number)
where number ~* '#\d{4}'
A stricter version of the regex would be '^#\d{4}$'
, so that it matches only strings that start with #
then have 4, and only 4 numbers, and then there is the end of the string.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a dba.stackexchange