2017-04-05 90 views
0

我正在處理紅移&想寫一些查詢,它將刪除第一次出現的括號內的消息。在紅移有正則表達式查找第一次出現

輸入: -

FR_3000 Error opening file [File_Location]. Operating system error message [The system cannot find the path specified.]. 

輸出: -

FR_3000 Error opening file []. Operating system error message [The system cannot find the path specified.]. 

我想下面的查詢,但未能解決問題..

select regexp_replace(description,'\[(.*?)\]','') from emp; 
+0

告訴我們它不能解決你的問題。這可能是錯誤的正則表達式,甚至錯誤的表或列名稱 –

回答

0

不知道是什麼你的問題是。我沒有任何環境可以在Redshift中進行測試。我猜根據你的標籤,那個替換太貪心了,結果變成FR_3000 Error opening file [].

一種方法是用

\1[]\2 

說明更換

^(.*?)\[.*?\](.*)$ 

^     Start of line 
( )    group 1 
    .*?    any number of character, reluctant match 
        (match at least as possible) 
     \[   follow by open square bracket 
     .*?   any number of char, reluctant match 
      \]  follow by closing square bracket 
      (.*) group 2, of any number of character 
       $ till the end 

根據紅移請調整的語法。

萬一紅移甚至不支持勉強量詞,改變正則表達式是這樣的:

^([^\[]*)\[[^\]]*\](.*)$ 

測試正則表達式中https://regex101.com/r/IDEvK3/1

1

紅移正規快件功能沒有組的任何概念捕獲,所以解決方案將不具有純正則表達式的純度。

只要你知道,「]」初審會經常來的第一個實例後,「[」,你可以使用:

select left(description, charindex('[', description)) || substring(description, charindex(']', description)) from emp; 

如果有可能,你有一個流浪「]」在您的字符串的開頭,你可以使用略少效率:

select left(description, charindex('[', description)) || substring(description, REGEXP_INSTR(description, '\]', charindex('[', description))) from emp; 

我們正在做的這些聲明有何第一左括號,這是charindex('[', description)位置,一切都在第一右括號前後正在採取一切,位於charindex(']', description),然後將它們與||運算符連接起來。

+0

謝謝傑森!它有幫助 –

相關問題