[英]regex to find first occurence
我正在研究redshift,並想編寫一些查詢,該查詢將僅刪除首次出現的括號內的消息。 在紅移那里
輸入:-
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;
Redshift正則表達式函數沒有任何組捕獲的概念,因此該解決方案不會具有純正則表達式的純度。
只要您知道']'的第一個實例總是會出現在'['的第一個實例之后,您可以使用:
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)
位置charindex(']', description)
,然后將它們與||
連接 操作員。
不知道您的問題是什么。 我沒有環境可以在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
請根據redshift調整語法。
如果redshift甚至不支持勉強的量詞,請將正則表達式更改為:
^([^\[]*)\[[^\]]*\](.*)$
在https://regex101.com/r/IDEvK3/1中測試正則表達式
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.