PostgreSQL:在双括号之间获取字符串

时间:2014-03-03 14:29:24

标签: sql regex postgresql search pattern-matching

我是PostgreSQL的新手,并决定稍微玩一下。因此,我想从Marked-Up文本中提取字符串,但是我没有得到我想要的结果。

为此,我有一个名为book的简单表和一个名为page的文本数据类型的列。

数据看起来像这样:

Simon the Sorcerer is a [[teenager]] transported into a fantasy world as a 
[[Sorcerer (person)|sorcerer]] dressed in a cloak and [[pointy hat]]; his 
cloak and hat are purple in the first game, but change to red for the rest 
of the series (aside from possible magical colour changes in the third game). 
He must use his logic and magical skills to solve puzzles as he progresses 
through the games. 

现在我想在方括号[[]]之间提取每个字符串。但是我该怎么做呢?或者没有插件就可以实现这一点?

我尝试使用LIKE的不同版本,但没有产生任何结果,例如:

SELECT * FROM book WHERE page LIKE '[[%]]';
SELECT * FROM book WHERE page LIKE '[[teenager]]';
...

我也用正则表达式玩了一下,但我只返回整个数据集而不是括号中的字符串:

SELECT * from book where page ~ '[^[[]+(?=\]])';

我的问题有解决方案吗?非常感谢帮助!

1 个答案:

答案 0 :(得分:2)

使用regexp_matches功能:

select regexp_matches(page,'[^[[]+(?=\]])','g') from book