Replace last occurrence of substring

ぐ巨炮叔叔 提交于 2020-12-06 20:20:31

问题


Given this string:

.ABC,.123,.FGH,.QDG

How can I most-efficiently use PL/SQL to output (note the ", and"):

abc, 123, fgh, and qdg

So far I've got LOWER(REPLACE('.ABC,.123,.FGH,.QDG', '.', ' ')), which yields

abc, 123, fgh, qdg

How do I get that "and" after "fgh,", but before "qdg" ("fgh, and qdg")? Must I use INSTR() and SUBSTR(), or is there a function that can just replace the last space with " and "?


回答1:


Building on what you used already... use regexp_replace with instr

with cte as(
select LOWER(REPLACE('.ABC,.123,.FGH,.QDG', '.', ' ')) as val from dual)
select regexp_replace(val,' ',' and ',instr(val ,' ',-1))
from cte;

or regexp_replace(val,', ',' and ',instr(val ,', ',-1)) if you want to get rid of the last comma too.




回答2:


This will do it:

select substr(text, 1, last_space_pos) || 'and' || substr(text, last_space_pos) new_text
from
(select text, instr(text, ' ', -1) last_space_pos
 from
 (select LOWER(REPLACE('.ABC,.123,.FGH,.QDG', '.', ' ')) text from dual)
);

The function call instr(text, ' ', -1) finds the position of the last space, and the substr calls break the string at that point so that we can insert 'and'. The use of nested select statements avoids having to repeat any complex expressions.



来源:https://stackoverflow.com/questions/34420359/replace-last-occurrence-of-substring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!