Using regular expressions in PostgreSQL

I wanted to search a table for values in a certain field which weren't valid positive integers. The values are strings, because this table is in the middle of being imported from a load of messy CSV files.

Here's what worked for me:

select distinct foo
from bar
where foo !~ '^[1-9][0-9]*$';

That is, where the value of foo doesn't consist of a digit 1–9 followed by zero or more other digits. I used the ^ and $ anchors to force a match of the whole string. You can use \d to match digits, instead of [0-9], but you have to double the backslash, because a regex is just a normal string literal to Postgres:

select distinct foo
from bar
where foo !~ '^[1-9]\\d*$';

The !~ operator returns true if the regex doesn't match. Use just ~ to return true when it does match. Add a * to the end of the operator to make the matching case-insensitive (i.e., ~* and !~*).

The regexes themselves are mostly POSIX compatible (unless you do some ugly tricks to change which ‘regex flavor’ you want). There are some borrowings from Perl as well, but they've changed things around a bit, so be careful.

see the official documentation on PostgreSQL regular expressions, for all the gory details.

< A first attempt at using the CLISP foreign function interface | UKUUG Linux 2004 Conference: day 1 >

Miniblog

(nuggets of inanity)

Tuesday Apr 24th 2007, 16:54 »
Just took the annual web design survey that AListApart do. I don't realy consider myself to be a web designer, but I have been doing a lot of HTML and CSS lately.
Monday Apr 23rd 2007, 18:23 »
Strange, there appears to be a bare-knuckle boxing match going on in the field outside my flat. Wish they wouldn't make so much noise about it.
Thursday Mar 1st 2007, 18:47 »
“In its written form, Hebrew has no vowels, making it the ideal language for texting.”
—Said in jest on some Radio 4 programme just now.

Archive: 2007 · 2006 · 2005 · 2004
Feed