postgres的grep-like查询

时间:2014-04-03 17:48:31

标签: regex postgresql

使用~运算符,可以很容易地找到表中列匹配给定正则表达式模式的所有行:

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

而不是描述,我想在模式的每个出现周围选择一段文本,所以如果一行包含

description = "aaaheloaaabbbhellobbbcccheloccc"

我希望输出3行:

"aaaheloaaa"
"bbbhellobbb"
"cccheloccc"

我称之为" grep-like"查询,因为它可以显示找到匹配项的列的提取。

2 个答案:

答案 0 :(得分:2)

我认为您需要regexp_split_to_table功能:

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

你可以像这样使用它:

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

回报:

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

所以在你的情况下,这将是:

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

答案 1 :(得分:2)

尝试类似:

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

如果没有WHERE子句,您将获得null行,其中没有匹配正则表达式。

相关问题