1

With the ~ operator, it is simple to find all lines in a table for which a column matches a given regexp pattern :

SELECT description from book where description ~ 'hell?o'
matches lines containing hello or helo

Instead of the description, I would like to SELECT a snippet of text around each occurences of the pattern, so if a line contains

description = "aaaheloaaabbbhellobbbcccheloccc"

I would like 3 lines as output :

"aaaheloaaa"
"bbbhellobbb"
"cccheloccc"

which I call a "grep-like" query because it can show extracts of the column where the match is found.

2 Answers 2

3

Try something like:

SELECT
  regexp_matches(description,'(.{0,3})('||'hell?o'||')(.{0,3})','g')
FROM
  book
WHERE description ~ 'hell?o'

Without the WHERE clause you will get null in rows, where were no matches for regexp.

Sign up to request clarification or add additional context in comments.

Comments

2

I think you need the regexp_split_to_table function:

http://www.postgresql.org/docs/current/static/functions-matching.html

And you can use it like this:

SELECT foo FROM regexp_split_to_table('the quick brown fox jumped over the lazy dog', E'\\s+') AS foo;

The return:

  foo   
--------
 the    
 quick  
 brown  
 fox    
 jumped 
 over   
 the    
 lazy   
 dog    
(9 rows)

So in your case this would look like:

select res from book, regexp_split_to_table(book.description, E'...hell?o...') res;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.