Postgres - 如果正則表達式匹配失敗,則返回預設值
我想嘗試正則表達式匹配,
null
如果失敗則返回。以下查詢嘗試查找字元串中的第一個數字。結果會忽略帶有 text 的條目
'blah'
。我更希望它返回一個null
值。這個問題可能與正則表達式無關,而與集合代數有關。我的直覺是,有一種優雅的方式可以做到這一點,不需要
left join
任何東西,儘管Google搜尋被證明是徒勞的。with test_data as ( select 'abc 123' as txt union select 'abc 456' as txt union select 'blah' as txt ) select txt, (regexp_matches(txt, '\d+'))[1] as first_num from test_data
雖然您的答案 解決了問題
regexp_matches()
,但更好的解決方案是使用更合適的函式來避免substring()
問題:WITH test_data(txt) AS ( VALUES (text 'abc 123') , ('abc 456') , ('blah') ) SELECT txt, substring(txt FROM '\d+') AS first_num FROM test_data;
完全符合您的需要:返回字元串中的第一個匹配項或
NULL
不匹配。
[substring(*string* FROM *pattern*)](https://www.postgresql.org/docs/current/functions-string.html#FUNCTIONS-STRING-SQL)
是標準的 SQL 語法。不要將其與其他事情混淆或做其他事情。
[substring(*string* [FROM int] [FOR int])](https://www.postgresql.org/docs/current/functions-string.html#FUNCTIONS-STRING-SQL)``[substring(*string* FROM *pattern* FOR *escape*)](https://www.postgresql.org/docs/current/functions-string.html#FUNCTIONS-STRING-SQL)
您還可以使用更短的、等效的、目前未記錄的 Postgres 實現
[substring(text, text)](https://www.postgresql.org/docs/current/functions-string.html#FUNCTIONS-STRING-SQL)
(用逗號 (,
) 代替FROM
)。用於
regexp_matches()
返回set的**所有匹配項。(請注意,單個正則表達式可能導致多個匹配,因此是一組文本數組)。除非您添加標誌以獲取所有行,否則您仍然只能獲得第一行(對於相同的正則表達式,其他匹配項 - 如果有的話)。有關的:'g'
FROM
為了避免複雜化,在 Postgres 10 之前的版本中將 set-returning 函式移動到列表中:或
regexp_match()
在 Postgres 10 或更高版本中使用以僅返回第一行。這也不會表現出原始問題:WITH test_data(txt) AS ( VALUES (text 'abc 123') , ('abc 456') , ('blah') ) SELECT txt, (regexp_match(txt, '\d+'))[1] AS first_num from test_data;
但僅
substring()
用於您的目的。db<>在這裡擺弄