2014-10-30 76 views
1

我有正则表达式的问题。regexp_replace POSTGRESQL

我想搜索的文字这样' A ' - (space, BIG SINGLE CHAR and SPACE)

SELECT regexp_replace(' A Text B Text C Text a Text', '(([ ]{1}[A-Z]{1,1}[ ]{1}))', ' \1 ', 'g') 

所以一切正常,但我想,以取代小焦这个单一的大字符。

SELECT regexp_replace(' A Text B Text C Text a Text', '(([ ]{1}[A-Z]{1,1}[ ]{1}))', lower(' \1 '), 'g') 

不工作。

如何使用功能在此匹配\1,例如lower()得到结果

a Text b Text c Text a Text

谢谢。

+0

你能发布预期的输出吗? – nu11p01n73R 2014-10-30 11:59:57

+0

'a Text b Text c Text a Text' 替换A B和C的小写 – lukasz 2014-10-30 12:02:39

回答

0

首先,你的正则表达式的一些注意事项的例子:

  • [ ]相同(单空格) - 单个字符不需要括号
  • {1}{1,1}是过时的,这是默认的行为(没有量词是指只有一个时间)

让我们澄清:lower(' \1 ')进行评估,以' \1 '之前你叫regexp_replace。因为这样,你的查询没有区别。

你不能用regexp_replace实现你想要的 - 你需要类似regexp_replace_eval(用自定义函数来转换你的替换),但这在PostgreSQL中不可用。

最你能做的,就是分裂您的原始字符串&在分部分取代:

select substring(string_agg(lower(substring(p for :length)) || substring(p from :length + 1), '') from :length + 1) 
from regexp_split_to_table(repeat(' ', :length) || :input, '(?=' || :pattern || ')') p 

-- in your case 

select substring(string_agg(lower(substring(p for 3)) || substring(p from 4), '') from 4) 
from regexp_split_to_table(' ' || ' A Text B Text C Text a Text', '(?= [A-Z])') p 

:这只有在固定长度的正则表达式模式工作。