如何使用正则表达式获取postgresql左边或右边的子字符串到第n个分隔符

时间:2013-12-18 01:34:32

标签: regex postgresql

假设我有一个变量字符串,如:

"Hello. Now is the time. Before. After "

我可以使用regexp_replace(Postgres)使用什么正则表达式来获取第二个或第n个分隔符字符左/右的子字符串,假设为“。”作为分隔符:

如果我想在第二个“。”上留下左侧字符串。我应该得到:

"Now is the time"

如果我想要第二个“。”的右侧字符串。我应该得到:

"Before"

这是在Postgresql 8.1(我知道......)

1 个答案:

答案 0 :(得分:0)

我使用string_to_array()解决了我的问题:

从第二个“。”获取左侧字符串:

SELECT (STRING_TO_ARRAY('Hello. Now is the time. Before. After ', '.'))[2];
 string_to_array  
------------------
  Now is the time

从第二个“。”获取右侧字符串:

SELECT (STRING_TO_ARRAY('Hello. Now is the time. Before. After ', '.'))[3];
 string_to_array 
-----------------
  Before

虽然我想知道如何使用regexp_replace(),因为我怀疑它可能会更快。