Contents / Previous / Next


Regular Expressions

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.

Regular expression operators:

Comparison Operator 
regular expression ~
regular expression, case-insensitive ~*
not equal to regular expression !~
not equal to regular expression, case-insensitive !~*


Regular expression special characters:

Test Special Characters
start ^
end $
any single character .
set of characters [ccc]
set of characters not equal [^ccc]
range of characters [c-c]
range of characters not equal [^c-c]
zero or one of previous character ?
zero or multiple of previous characters *
one or multiple of previous characters +
OR operator |


Note that the caret (^) has a different meaning outside and inside square brackets ([]).

Use of a backslash to mask special characters. For example, to test for a dollar sign, use \$. To test for an asterisk, use \*. To test for a literal backslash, use two backslashes (\\).


Examples of regular expressions

Test Operation
begins with D ~ '^D'
contains D ~ 'D'
D in second position ~ '^.D'
begins with D and contains e ~ '^D.*e'
begins with D, contains e, and then f ~ '^D.*e.*f'
contains A, B, C, or D ~ '[A-D]' or  ~ '[ABCD]'
contains A or a ~* 'a' or  ~ '[Aa]'
does not contain D !~ 'D'
does not begin with D !~ '^D' or  ~ '^[^D]'
begins with D, with one optional leading space ~ '^ ?D'
begins with D , with optional leading spaces ~ '^ *D'
begins with D, with at least one leading space ~ '^ +D'
ends with G, with optional trailing spaces ~ 'G *$'


Example:

SELECT * FROM stud WHERE name !~* '.*o.*' ; id | name | semester | diploma | gender ----+------+----------+---------+-------- 1 | fred | 2 | bio | m 2 | lisa | 2 | bio | f