Regular expressions allow more powerful comparisons than LIKE and NOT LIKE. Regular expression comparisons are a unique feature of POSTGRESQL. They are very common in Unix, such as in the Unix grep command. 8.4
Table lists the regular expression
operators , and Table
|
Although regular expressions are powerful, they can be complex to
create. Table shows some examples,
and Figure
shows selected
queries using regular expressions. For a description of each query,
see the comment above it.
|
Figure shows two
more complex regular expressions.
test=> -- firstname ends with n
test=> SELECT * FROM friend
test-> WHERE firstname ~ 'n *$'
test-> ORDER BY firstname;
firstname | lastname | city | state | age
-----------------+----------------------+-----------------+-------+-----
Dean | Yeager | Plymouth | MA | 24
(1 row)
test=> -- firstname contains a non-S character
test=> SELECT * FROM friend
test-> WHERE firstname ~ '[^S]'
test-> ORDER BY firstname;
firstname | lastname | city | state | age
-----------------+----------------------+-----------------+-------+-----
Dean | Yeager | Plymouth | MA | 24
Dick | Gleason | Ocean City | NJ | 19
Ned | Millstone | Cedar Creek | MD | 27
Sandy | Gleason | Ocean City | NJ | 25
Sandy | Weber | Boston | MA | 33
Victor | Tabor | Williamsport | PA | 22
(6 rows)
The first query demonstrates how to properly test for a trailing
n. Because CHAR() columns contain
trailing spaces to fill the column, you must test for possible trailing
spaces. (See Section for
complete coverage on character data types.) The second query might
seem surprising. Some might think that it returns rows that do not
contain an S. Actually, it returns all rows that have any
character that is not an S. For example, Sandy contains
characters that are not S, such as a, n, d, and y,
so that row is returned. The test would prevent rows containing only
S's from being printed.
You can also test for the literal characters listed in Table .
Use of a backslash removes any special meaning from the character
that follows it. For example, to test for a dollar sign, use \$.
To test for an asterisk, use \*. To test
for a literal backslash, use two backslashes (\\).
Because regular expressions are so powerful, creating them can be challenging. Try some queries on the friend table until you are comfortable with regular expression comparisons.