问题
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