2014-10-30 103 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 

:這隻有在固定長度的正則表達式模式工作。