我正在嘗試使用regexp_subst來拆分分隔字串。當分隔欄位為空時,我遇到了一個問題。regexp_substr忽略空值并移至下一次出現的分隔符。有沒有辦法做到這一點regexp_substr?如果不是,您使用什么替代方案?
--Expecting hello, gets hello
select regexp_substr('hello@@world', '[^@] ', 1, 1)
from dual;
--Expecting null, gets world
select regexp_substr('hello@@world', '[^@] ', 1, 2)
from dual;
--Expecting world, gets null
select regexp_substr('hello@@world', '[^@] ', 1, 3)
from dual;
編輯:試過這個,但它只適用于 | 這不是一個選擇
uj5u.com熱心網友回復:
根據 Matbailie 在上述評論中的輸入進行回答
select regexp_substr('hello@@world', '(.*?)(@|$)', 1, 1,NULL,1)
from dual
union all
--Expecting null, gets null
select regexp_substr('hello@@world', '(.*?)(@|$)', 1, 2,NULL,1)
from dual
union all
--Expecting world, gets world
select regexp_substr('hello@@world', '(.*?)(@|$)', 1, 3,NULL,1)
from dual;
uj5u.com熱心網友回復:
您不需要正則運算式。它可以通過遞回子查詢中的簡單(和更快)字串函式來完成:
WITH data (value) AS (
SELECT 'hello@@world' FROM DUAL
),
bounds (value, start_pos, end_pos) AS (
SELECT value,
1,
INSTR(value, '@', 1)
FROM data
UNION ALL
SELECT value,
end_pos 1,
INSTR(value, '@', end_pos 1)
FROM bounds
WHERE end_pos > 0
)
SEARCH DEPTH FIRST BY value SET order_id
SELECT CASE end_pos
WHEN 0
THEN SUBSTR(value, start_pos)
ELSE SUBSTR(value, start_pos, end_pos - start_pos)
END AS item
FROM bounds;
哪個輸出:
物品 你好 無效的 世界
或者,如果您想要列(而不是行)中的資料:
WITH data (value) AS (
SELECT 'hello@@world' FROM DUAL
),
bounds (value, pos1, pos2) AS (
SELECT value,
INSTR(value, '@', 1, 1),
INSTR(value, '@', 1, 2)
FROM data
)
SELECT SUBSTR(value, 1, pos1 - 1) AS item1,
SUBSTR(value, pos1 1, pos2 - pos1 - 1) AS item2,
SUBSTR(value, pos2 1) AS item3
FROM bounds
哪個輸出:
專案1 專案2 專案3 你好 無效的 世界
如果您確實想使用(較慢的)正則運算式,那么:
WITH data (value) AS (
SELECT 'hello@@world' FROM DUAL
)
SELECT item
FROM data d
CROSS JOIN LATERAL(
SELECT REGEXP_SUBSTR( d.value, '(.*?)(@|$)', 1, LEVEL, NULL, 1) AS item
FROM DUAL
CONNECT BY LEVEL < REGEXP_COUNT( d.value, '(.*?)(@|$)')
)
或者,對于列:
WITH data (value) AS (
SELECT 'hello@@world' FROM DUAL
)
SELECT REGEXP_SUBSTR(value, '(.*?)(@|$)', 1, 1, NULL, 1) AS item1,
REGEXP_SUBSTR(value, '(.*?)(@|$)', 1, 2, NULL, 1) AS item2,
REGEXP_SUBSTR(value, '(.*?)(@|$)', 1, 3, NULL, 1) AS item3
FROM data
(兩者都具有與上述相同的輸出)
db<>在這里擺弄
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/494507.html
