使用Oracle SQL在字符之间添加管道分隔符

时间:2016-09-06 14:28:23

标签: sql regex oracle

我有一个字符串' foobar'我需要喜欢的是' f | o | o | b | a | R'在查询中(Oracle 12 SQL)。那是" | "在每个字母之间但不在最后。字符串的长度各不相同,可能为空。

更多例子:

'富'> ' f | o | O'

NULL> ''

我尝试过使用regexp_replace

select regexp_replace(foobar,'.',' | ') from dual

以及许多其他组合。我找到了似乎在Oracle中不起作用的正则表达式的示例,例如(?< =。)(?!$)。

非常感谢任何帮助

2 个答案:

答案 0 :(得分:6)

regexp_replace

将完成工作:

select regexp_replace('foobar','(.)','\1 | ') from dual

会给你

f | o | o | b | a | r | 

摆脱最后一个栏的简单方法(编辑,遗漏空白):

select substr(regexp_replace('foobar','(.)','\1 | '),1, length('foobar')*4-3) from dual

输出

f | o | o | b | a | r

概念证明(只是为了满足Raj_te我真的没有看到什么是错的)

with t as 
(
select 1 as id, 'foobar' as field1 from dual union all
select 2 as id, 'fooobar' as field1 from dual union all
select 3 as id, 'foooobar' as field1 from dual union all
select 4 as id, 'fooooobar' as field1 from dual union all
select 5 as id, 'foooooobar' as field1 from dual union all
select 6 as id, 'fooooooobar' as field1 from dual union all
select 7 as id, 'foooooooobar' as field1 from dual )
select substr(regexp_replace(field1,'(.)','\1 | '),1, length(field1)*4-3) 
 from t
 order by id;

<强>输出

f | o | o | b | a | r
f | o | o | o | b | a | r
f | o | o | o | o | b | a | r
f | o | o | o | o | o | b | a | r
f | o | o | o | o | o | o | b | a | r
f | o | o | o | o | o | o | o | b | a | r
f | o | o | o | o | o | o | o | o | b | a | r

答案 1 :(得分:1)

问题是你需要一个后退参考来获得你的角色。然后另一个问题是表达式末尾的|。这是一种方法:

select regexp_replace(regexp_replace(foobar, '(.)', '\1 |'), ' \| ', '')

或者,或许更简单:

select substr(regexp_replace(foobar, '(.)', ' | \1'), 4)