Using Regular Expressions in Postgres Text Fields

Heitor Helmer Herzog
1 min readMar 2, 2017

--

Regular expressions are a set of key combinations that allow people to search for specific characters, thus allowing a wide variety of control in a text environment. They are a common feature of many applications, including text editors , Command-line utilities, and programming languages ​​to search and manipulate text bodies based on certain patterns.

See the examples below:
The simplest query uses the operator, ~, followed by characters quoted literals. These examples return all records that contain specific characters (s) as defined by the criteria:

SELECT register FROM table WHERE register ~ ‘1’;
SELECT register FROM table WHERE register ~ ‘a’;
SELECT register FROM table WHERE register ~ ‘A’;
SELECT register FROM table WHERE register ~ ‘3a’;

The addition of *, after ~ makes the search query case-insensitive

SELECT register FROM table WHERE register ~* ‘a’;
SELECT register FROM table WHERE register ~* ‘3a’;

The,!, Modifies the ~ operator and excludes strings containing the character (s):
SELECT record FROM table WHERE record! ~ ‘1’;
Here are some more examples of searching for all the letters of the alphabet:
SELECT record FROM table WHERE record ~ ​​’[a-z]’
And here only numbers:
SELECT record FROM table WHERE record ~ ​​’[^ 0–9]’

--

--

Heitor Helmer Herzog
Heitor Helmer Herzog

Written by Heitor Helmer Herzog

Software developer, In love with games and the industry. Let’s code! About me: www.linkedin.com/in/heitorhherzog

No responses yet