如何使用Oracle SQL将字符串中逗号的最后一个实例替换为'and'?
SELECT 'Bats, Bars, Beers' AS "WORD_SOUP" FROM DUAL;
我想输出“蝙蝠,酒吧和啤酒”
答案 0 :(得分:0)
您可以使用正则表达式:
select regexp_replace('Bats, Bars, Beers', ',\s*([^,]+)$', ' and \1') as word_soup
from dual
regexp模式搜索直到字符串末尾没有逗号的逗号,并捕获其后的内容;然后我们将逗号替换为“和”。
| WORD_SOUP | | :------------------- | | Bats, Bars and Beers |
我没有保留最后一个逗号-因为这对我来说更有意义-但是,如您期望的结果所示,如果您愿意,则:
select regexp_replace('Bats, Bars, Beers', ',\s*([^,]+)$', ', and \1') as word_soup
from dual
答案 1 :(得分:0)
或者,更容易理解:
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
字符串中,替换','
' and'
1
字符串中第col
的位置开始,last regexp_count(col, ',')
(即计数逗号)答案 2 :(得分:0)
使用简单的字符串函数在最后一个逗号之前和之后查找子字符串,并将它们之间的 and
连接起来:
SELECT SUBSTR( word_soup, 1, INSTR( word_soup, ',', -1 ) )
|| ' and'
|| SUBSTR( word_soup, INSTR( word_soup, ',', -1 ) + 1 ) AS replaced
FROM (
SELECT 'Bats, Bars, Beers' AS WORD_SOUP
FROM DUAL
);
输出:
| REPLACED | | :-------------------- | | Bats, Bars, and Beers |
db <>提琴here