使用Oracle SQL将字符串中的最后一个逗号替换为“and”
如何使用Oracle SQL将字符串中逗号的最后一个实例替换为“and”使用Oracle SQL将字符串中的最后一个逗号替换为“and”,sql,string,oracle,Sql,String,Oracle,如何使用Oracle SQL将字符串中逗号的最后一个实例替换为“and” SELECT 'Bats, Bars, Beers' AS "WORD_SOUP" FROM DUAL; 我希望这个输出“蝙蝠、酒吧和啤酒”您可以使用正则表达式: select regexp_replace('Bats, Bars, Beers', ',\s*([^,]+)$', ' and \1') as word_soup from dual regexp模式搜索一个逗号,该逗号在字符串结束之
SELECT 'Bats, Bars, Beers' AS "WORD_SOUP" FROM DUAL;
我希望这个输出“蝙蝠、酒吧和啤酒”您可以使用正则表达式:
select regexp_replace('Bats, Bars, Beers', ',\s*([^,]+)$', ' and \1') as word_soup
from dual
regexp模式搜索一个逗号,该逗号在字符串结束之前不后跟任何逗号,并捕获它后面的内容;然后我们将逗号替换为and
:
或者,更容易理解:
SQL> with test (col) as
2 (select 'Bats, Bars, Beers' from dual)
3 select regexp_replace(col, ',', ' and', 1, regexp_count(col, ',')) result
4 from test;
RESULT
--------------------
Bats, Bars and Beers
SQL>
第3行解释:
在col字符串中,替换
逗号“,”
用“和”
从列字符串中的第一个位置开始,然后
替换其最后一个regexp_countcol“,”即计数逗号出现的次数
使用简单字符串函数查找最后一个逗号前后的子字符串,并在它们之间连接: 选择SUBSTR单词“汤”,1,INSTR单词“汤”,,-1 ||“还有” ||替换为子单词“汤”,INSTR单词“汤”、“,-1+1 从…起 选择“蝙蝠、酒吧、啤酒”作为WORD_汤 来自双重 ; 产出:
dbfiddle存在一个与此相关的问题,但此示例略有不同-我看到了该示例,但该示例未在其他单词之间包含空格
select regexp_replace('Bats, Bars, Beers', ',\s*([^,]+)$', ', and \1') as word_soup
from dual
SQL> with test (col) as
2 (select 'Bats, Bars, Beers' from dual)
3 select regexp_replace(col, ',', ' and', 1, regexp_count(col, ',')) result
4 from test;
RESULT
--------------------
Bats, Bars and Beers
SQL>
| REPLACED |
| :-------------------- |
| Bats, Bars, and Beers |