我使用了函数regexp_substr(STR,'[^|]+',1,2)
,
它在某些情况下运行良好,但对于空方案,它给出了第三个值,
1|CAT|DOG
3|HARRY|GOAT|STACK
6||LION|TIGER --this row should return null, but the above function gives me LION
预期产出:
CAT
HARRY
(null)
答案 0 :(得分:2)
@Gary_W has written about使用该正则表达式模式来分割字符串的问题,正是因为它如何处理空标记。 (和is on a mission...)
该帖子中的替代方法也适用于此,管道分隔符已转义:
with t (str) as (
select '1|CAT|DOG' from dual
union all select '3|HARRY|GOAT|STACK' from dual
union all select '6||LION|TIGER' from dual
)
select str, regexp_substr(str, '(.*?)(\||$)', 1, 2, null, 1) from t;
STR REGEXP_SUBSTR(STR,
------------------ ------------------
1|CAT|DOG CAT
3|HARRY|GOAT|STACK HARRY
6||LION|TIGER
同样适用于第三个要素:
select str, regexp_substr(str, '(.*?)(\||$)', 1, 3, null, 1) from t;
STR REGEXP_SUBSTR(STR,
------------------ ------------------
1|CAT|DOG DOG
3|HARRY|GOAT|STACK GOAT
6||LION|TIGER LION
第四个:
select str, regexp_substr(str, '(.*?)(\||$)', 1, 4, null, 1) from t;
STR REGEXP_SUBSTR(STR,
------------------ ------------------
1|CAT|DOG
3|HARRY|GOAT|STACK STACK
6||LION|TIGER TIGER
答案 1 :(得分:1)
你的功能是返回正确的结果。当你运行你的功能时,
function regexp_substr(STR,'[^|]+',1,2)
at
6||LION|TIGER
Oracle没有找到任何' NULL
' ||
之间的值。如果在||
之间放置一个空格,它将返回正确的结果。见下文:
查询:
WITH tbl (str)
AS (SELECT '1|CAT|DOG' FROM DUAL
UNION ALL
SELECT '3|HARRY|GOAT|STACK' FROM DUAL
UNION ALL
SELECT '6| |LION|TIGER' FROM DUAL) --<-- Space added between | |
SELECT REGEXP_SUBSTR (STR,
'[^|]+',
1,
2
)
FROM tbl
或者,您可以在查询中用||
替换所有| |
个字符并获得结果。
WITH tbl (str)
AS (SELECT '1|CAT|DOG' FROM DUAL
UNION ALL
SELECT '3|HARRY|GOAT|STACK' FROM DUAL
UNION ALL
SELECT '6||LION|TIGER' FROM DUAL)
SELECT REGEXP_SUBSTR ((replace(STR,'||','| |')),
'[^|]+',
1,
2)
FROM tbl