Wednesday, January 2nd, 2008...5:22 pm

Postgres select replace with regular expression

Jump to Comments

Postgres seriously kicks ass, here's a quick way to do a substring based on a regular expression. A Co-worker wanted to get the first word out of a column that contained a sentence. If we were using something lame like oracle we'd have to do gymnastics to do that.

It's a one-liner in postgres.

SELECT substring('this is a sentence' FROM '^(.+?)\\s.+$')

So we're selecting out the group that is a series of characters at the start of a line (column) before a space. Epic win.

Leave a Reply